Skip to content

Instantly share code, notes, and snippets.

@betabites
Last active June 10, 2024 04:40
Show Gist options
  • Save betabites/58cde09fad3bbb931ae858ee936d0c50 to your computer and use it in GitHub Desktop.
Save betabites/58cde09fad3bbb931ae858ee936d0c50 to your computer and use it in GitHub Desktop.
A wrapper function for async express.js middleware/route handlers.
import {NextFunction} from "express";
export function AsyncEndpoint(originalMethod: (req: Request, res: Response, next: NextFunction) => PromiseLike<any>) {
async function replacementMethod(req: Request, res: Response, next: NextFunction) {
try {
await originalMethod(req, res, next)
next()
} catch (e) {
next(e)
}
}
return replacementMethod
}
@betabites
Copy link
Author

This function can be used to wrap any express.js middleware you've written. The function will automatically catch any errors in your async function and pass the error back into express.js for proper handling.

An example use case might be:

EXPRESS_APP.get("/error", AsyncEndpoint(async (req, res) => {
    console.log("doing some stuff...")
    
    throw new Error("Oh no! An error occurred!")
}))

This should help keep your code clean and implement centralised error handling on your express app, rather than having to do messy error handling on all your async endpoints individually.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment