Skip to content

Instantly share code, notes, and snippets.

@lucas-janon
Created June 12, 2018 01:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucas-janon/db7c247d073a6c2c716f7ccef1564c26 to your computer and use it in GitHub Desktop.
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)
// 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