Skip to content

Instantly share code, notes, and snippets.

Last active March 1, 2017 11:58
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
// catch any errors in the promise and either forward them to next(err) or ignore them
const catchErrors = fn => (req, res, next) => fn(req, res, next).catch(next)
const ignoreErrors = fn => (req, res, next) => fn(req, res, next).catch(() => next())
// wrap my routes in those helpers functions to get error handling
app.get('/sendMoney/:amount', catchErrors(sendMoney))
// use our ignoreErrors helper to ignore any errors in the logging middleware
app.get('/doSomethingElse', ignoreErrors(logSomething), doSomethingElse)
// controller method can throw errors knowing router will pick it up
export async function sendMoney(req, res, next) {
if (!req.param.amount) {
throw new Error('You need to provide an amount!')
await Money.sendPayment(amount) // no try/catch needed
res.send(`You just sent ${amount}`)
// basic async logging middleware
export async function logSomething(req, res, next) {
// ...
throw new Error('Something went wrong with your logging')
// ...
Copy link

johnib commented Feb 22, 2017

What's the difference between:



.catch(() => next()) ?

Copy link

TimonVS commented Feb 22, 2017

@johnib .catch(next) passes all parameters to the next function. It's actually just a shorthand for .catch((...args) => next(...args))

Copy link

buzzdan commented Feb 23, 2017

catch(next) is actually like catch(error => next(error))

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