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.
In order to run multiple async/await calls in parallel, all we need to do is add the calls to an array, and then pass that array as an argument to Promise. all() . Promise. all() will wait for all the provided async calls to be resolved before it carries on(see Conclusion for caveat).
We can handle this in two ways: We call thisThrows() in an async function and await the thisThrows() function. We chain the thisThrows() function call with a . catch() call.
Since you're working with what looks like synchronous code, async functions can use try... catch to handle any errors. try... catch is the most common way to handle exceptions when using async/await.
In my view, unless a library or legacy codebase forces you to use then/catch , the better choice for readability and maintainability is async/await .
Yes, you can easily write such a wrapper for asynchronous functions as well - just use async
/await
:
function wrapper(f) {
return async function() {
// ^^^^^
try {
return await f.apply(this, arguments);
// ^^^^^
} catch(e) {
customErrorHandler(e)
}
}
}
Or you use promises directly, like in this example that is more tailored to express (especially with the number of parameters):
function promiseWrapper(fn) {
return (req, res, next) => {
fn(req, res).catch(next);
};
}
A similar answer here hope can help you
const sthError = () => Promise.reject('sth error');
const test = opts => {
return (async () => {
// do sth
await sthError();
return 'ok';
})().catch(err => {
console.error(err); // error will be catched there
});
};
test().then(ret => {
console.log(ret);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With