有没有办法包装等待/异步try / catch块到每个功能? [英] Is there a way to wrap an await/async try/catch block to every function?
问题描述
所以我正在使用express.js并查看使用async / await与节点7.有没有办法,我仍然可以捕获错误,但摆脱try / catch块?也许函数包装器?我不知道这将如何实际执行该函数的代码,并调用 next(err)
。
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);
}
}
这样的东西...?
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);
}
编辑:
更类似的东西:
var wrapper = function(f) {
return function() {
try {
f.apply(this, arguments);
} catch(e) {
customErrorHandler(e)
}
}
}
这将以某种方式处理try / catch块但不起作用:
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);
});
请参阅有没有办法为Javascript中的每个函数添加try-catch?为非异步示例。
See Is there a way to add try-catch to every function in Javascript? for the non-async example.
推荐答案
是的,您可以轻松地为异步函数编写这样的包装器 - 只需使用 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)
}
}
}
或者您直接使用承诺,就像在这个例子中,更适合表达(特别是参数的数量): p>
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);
};
}
这篇关于有没有办法包装等待/异步try / catch块到每个功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!