Last active
July 25, 2023 23:39
-
-
Save adamelliotfields/18d39c718bdbbdce5a16de1e8b81d6f3 to your computer and use it in GitHub Desktop.
Express Async Handler Wrapper to Prevent Unhandled Promise Rejections
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
/** | |
* @template {(...args: any[]) => Promise<any>} T | |
* @param {T} fn | |
* @returns {(...args: Parameters<T>) => Promise<ReturnType<T>|void>} | |
*/ | |
export const wrap = (fn) => (...args) => fn(...args).catch(args[2]); |
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 type { | |
NextFunction, | |
Request, | |
RequestHandler, | |
Response, | |
} from 'express'; | |
/** | |
* Wrap an async function and call next(err) if the Promise rejects. | |
* @see https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/#using-es7-asyncawait | |
*/ | |
export function wrap(handler: RequestHandler): RequestHandler { | |
return (req: Request, res: Response, next: NextFunction) => handler(req, res, next).catch(next); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment