Skip to content

Instantly share code, notes, and snippets.

@adamelliotfields
Last active July 25, 2023 23:39
Show Gist options
  • Save adamelliotfields/18d39c718bdbbdce5a16de1e8b81d6f3 to your computer and use it in GitHub Desktop.
Save adamelliotfields/18d39c718bdbbdce5a16de1e8b81d6f3 to your computer and use it in GitHub Desktop.
Express Async Handler Wrapper to Prevent Unhandled Promise Rejections
/**
* @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]);
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