Skip to content

Instantly share code, notes, and snippets.

@smddzcy
Created November 13, 2018 12:29
Show Gist options
  • Save smddzcy/c8cfc5e56d4eb8152875137b776a213a to your computer and use it in GitHub Desktop.
Save smddzcy/c8cfc5e56d4eb8152875137b776a213a to your computer and use it in GitHub Desktop.
Default error handling for Express routes
['get', 'post', 'put', 'delete'].forEach((method) => {
const originalFn = app[method];
app[method] = function fn(...args) {
const routeFn = args[args.length - 1];
const firstArgs = args.slice(0, args.length - 1);
const newRouteFn = (req, res, next) => {
try {
if (routeFn.constructor.name === 'AsyncFunction') {
return routeFn(req, res, next).catch(next);
}
return routeFn(req, res, next);
} catch (err) {
return next(err);
}
};
return originalFn.call(this, ...firstArgs, newRouteFn);
};
});
@smddzcy
Copy link
Author

smddzcy commented Nov 13, 2018

Example usage:

app.get('/test', (req, res) => {
  // undefined variable, will throw an error. normally, this can't be caught by any Express error handler, 
  // but our dirty little hack above will catch it.
  iAmUndefined;

  return res.send('wow');
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment