以下tryCatch装饰器无法捕获错误。
const TryCatchWrapper = (target, key, descriptor) => {
const fn = descriptor.value;
descriptor.value = (...args) => {
try {
fn.apply(this, args);
} catch (error) {
console.log('Entered Catch----->');
const [,, next] = args;
next(error);
}
};
};
尝试在以下课程中使用 -
class CustomerDetails {
@TryCatchWrapper
async getCustomerSummary(req, res, next) {
throw new Error('Whoops!!!');
}
}
问题: - '输入Catch ----->' 永远不会被打印。
答案 0 :(得分:5)
因为getCustomerSummary
是一个async
函数。 async
函数从不抛出;相反,它返回一个被拒绝的承诺。 (内部 async
函数,当您在try
周围使用catch
/ await
时,会转为承诺拒绝处理。但是在非 - async
函数调用async
函数,该糖未被应用。)
您需要修改装饰器以查看函数的返回值,如果它是一个承诺,则处理承诺拒绝。
答案 1 :(得分:1)
实际上,您的方法没有错。您只是忘记了await
来获取fn.apply
的结果,并将descriptor.value
设置为async
的功能。
在此处查看示例https://stackblitz.com/edit/typescript-dycwcg
const TryCatchWrapper = (target, key, descriptor) => {
const fn = descriptor.value;
descriptor.value = async (...args) => {
try {
await fn.apply(this, args);
} catch (error) {
console.log('Entered Catch----->');
const [,, next] = args;
next(error);
}
};
};