diff --git a/app/src/api/routes/asyncController.ts b/app/src/api/routes/asyncController.ts new file mode 100644 index 00000000..333f664b --- /dev/null +++ b/app/src/api/routes/asyncController.ts @@ -0,0 +1,17 @@ +import { Request, Response, NextFunction } from 'express'; + +/** + * A wrapper for controller functions that return a Promise, enabling them to be used with Express + * Without this wrapper, Promise rejections caused by an error in the controller will not be passed properly + * to subsequent middleware layers. + * @param fn the async controller function to be wrapped + * @returns controller function which handles async errors correctly + */ +function asyncController(fn: (req: Request, res: Response, next: NextFunction) => Promise) { + return (req: Request, res: Response, next: NextFunction) => { + Promise.resolve(fn(req, res, next)) + .catch(next); + }; +} + +export default asyncController; \ No newline at end of file