Last active
March 1, 2017 11:58
-
-
Save xjamundx/dcac1ca327ff2cfd20082711cc2ea9d9 to your computer and use it in GitHub Desktop.
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
// 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 .catch(next)
passes all parameters to the next
function. It's actually just a shorthand for .catch((...args) => next(...args))
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
What's the difference between:
.catch(next)
and
.catch(() => next())
?