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函数中,这个函数没有被应用)。

您需要修改装饰器来查看函数的返回值,如果是承诺,则处理承诺拒绝。