TryCatch Decorator没有捕获错误

Let*_*see 2 javascript jquery node.js

以下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);
    }
  };
};
Run Code Online (Sandbox Code Playgroud)

试着在下面的课程中使用 -

class CustomerDetails {

  @TryCatchWrapper
  async getCustomerSummary(req, res, next) {
      throw new Error('Whoops!!!');
  }
}
Run Code Online (Sandbox Code Playgroud)

问题: - '进入Catch ----->'永远不会被打印出来.

T.J*_*der 5

这是因为getCustomerSummary是一种async功能.一个async函数从不抛出; 相反,它返回一个被拒绝的承诺.(里面async功能,当您使用try/ catch左右await,这被化作承诺拒绝处理,但在非async函数调用的async函数,糖不适用.)

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


Edu*_*cko 5

实际上,您的方法没有任何问题。您只是忘记await从结果中获取fn.apply并设置descriptor.valueasasync函数。请参阅此处的示例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);
    }
  };
};
Run Code Online (Sandbox Code Playgroud)