Last active
June 10, 2024 04:40
-
-
Save betabites/58cde09fad3bbb931ae858ee936d0c50 to your computer and use it in GitHub Desktop.
A wrapper function for async express.js middleware/route handlers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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.