问题
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.
回答1:
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);
};
}
回答2:
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);
});
来源:https://stackoverflow.com/questions/41349331/is-there-a-way-to-wrap-an-await-async-try-catch-block-to-every-function