Skip to content

Instantly share code, notes, and snippets.

@xjamundx
Last active March 1, 2017 11:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xjamundx/dcac1ca327ff2cfd20082711cc2ea9d9 to your computer and use it in GitHub Desktop.
Save xjamundx/dcac1ca327ff2cfd20082711cc2ea9d9 to your computer and use it in GitHub Desktop.
// 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')
// ...
}
@johnib
Copy link

johnib commented Feb 22, 2017

What's the difference between:

.catch(next)

and

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

@TimonVS
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))

@buzzdan
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