TryCatch Decorator不捕捉错误
以下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!!!'); } }
问题: – “input的Catch —–”不会被打印。
这是因为getCustomerSummary
是一个async
函数。 一个async
函数不会抛出; 相反,它会返回被拒绝的承诺。 ( 在一个async
函数里面 ,当你使用try
/ catch
时候,它会变成承诺拒绝处理,但是在一个调用async
函数的非async
函数中,这个函数没有被应用)。
您需要修改装饰器来查看函数的返回值,如果是承诺,则处理承诺拒绝。