Created
November 13, 2018 12:29
-
-
Save smddzcy/c8cfc5e56d4eb8152875137b776a213a to your computer and use it in GitHub Desktop.
Default error handling for Express routes
This file contains hidden or 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
['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); | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: