Created
June 12, 2018 01:10
-
-
Save lucas-janon/db7c247d073a6c2c716f7ccef1564c26 to your computer and use it in GitHub Desktop.
Async/Await wrapper for express routes (to avoid try/catching every route)
This file contains 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
// Adds a .catch to the express callback to handle errors that happen in async/await functions | |
// you should wrap every route with this handler | |
// ie: errorHandler((req, res) => res.send(JSON.stringify(res.locals.user))) | |
const errorHandler = fn => (req, res, next) => { | |
Promise.resolve(fn(req, res, next)) | |
.catch(error => { | |
if (process.NODE_ENV === 'development') console.log(require('util').inspect(error)) | |
next(error) | |
}) | |
} | |
module.exports = asyncErrorHandler |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment