Skip to content

Instantly share code, notes, and snippets.

@olehcambel
Created March 30, 2019 13:04
Show Gist options
  • Save olehcambel/418edc9ed259aa95e7d71bcc3020b748 to your computer and use it in GitHub Desktop.
Save olehcambel/418edc9ed259aa95e7d71bcc3020b748 to your computer and use it in GitHub Desktop.
async error handling with express
import { asyncWrap } from './async-wrap';
const app = express();
asyncWrap();
import { Request, Response, NextFunction } from 'express';
const Layer = require('express/lib/router/layer');
export const asyncWrap = (): void => {
Layer.prototype.handle_request = async function handle(
req: Request,
res: Response,
next: NextFunction,
) {
const fn = this.handle;
// not a standard request handler
if (fn.length > 3) return next();
try {
await fn(req, res, next);
} catch (err) {
next(err);
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment