So i'm using express.js and looking into using async/await with node 7. Is there a way that I can still catch errors but get rid of the try/catch block? Perhaps a function wrapper? I'm not sure how this would actually execute the function's code and also call next(err)
.
exports.index = async function(req, res, next) {
try {
let user = await User.findOne().exec();
res.status(200).json(user);
} catch(err) {
next(err);
}
}
Something like this...?
function example() {
// Implements try/catch block and then handles error.
}
exports.index = async example(req, res, next) {
let user = await User.findOne().exec();
res.status(200).json(user);
}
EDIT:
Something more similar to this:
var wrapper = function(f) {
return function() {
try {
f.apply(this, arguments);
} catch(e) {
customErrorHandler(e)
}
}
}
This would somehow handle the try/catch block but doesn't work:
exports.index = wrapper(async example(req, res, next) {
let user = await User.findOne().exec();
res.status(200).json(user);
});
See Is there a way to add try-catch to every function in Javascript? for the non-async example.
.then()
and.catch()
. What isawait
buying you. Error handling needs to be there. You can't just wish it away to some other function. – Finickythen
statements when they may need to fork. The above code is just there as a demonstrative example. – Ullyot.then()
handlers in what you have above - you can just chain if there's a need for more than one async operation to be sequenced. You can't hide error handling and trying to is a fool's errand. A big downfall ofawait
is that people tend to just shortchange error handling whereas the need for it is more obvious with.then()
and.catch()
. You can still do it withawait
, but it needs `try/catch. Please use real-world code that is as complicated as what you're trying to ask about. – FinickyIs there a way that I can still catch errors but get rid of the try/catch block scaffold
– Ullyotasync/await
is not part of ES7. – Turnstile