【问题标题】:method babel decorators isn't executed方法 babel 装饰器未执行
【发布时间】:2018-07-26 11:58:23
【问题描述】:

我正在使用babel 7 decorator plugin,我有一个简单的类,我想在一个简单的 try catch 包装器中装饰每个方法。

这就是我们所做的:

const errorHandler = () => {
  return (target, property, descriptor) => {
    try {
      return descriptor
    } catch (e) {
      console.error('error from the decorator', e)
    }
  }
}

这是我班级的一个示例:

class Example {
  @errorHandler
  addComponent() {
    throw new Error('Error')
  }
}

但是当我执行函数时,它不会在执行前抛出装饰器,只会在类初始化时进行预评估。

有什么想法吗?

【问题讨论】:

    标签: javascript babeljs babel-decorator


    【解决方案1】:

    您正在返回descriptor,它是一个函数对象,它由您的try/catch 块之外的调用者执行。要拦截异常 - 您应该自己执行descriptor

    正确的代码是:

    const errorHandler = (target, property, descriptor) => {
      const original = descriptor.value;
      if (typeof original === 'function') {
        descriptor.value = async function(...args) {
          try {
            return await original.apply(this, args);
          } catch (e) {
            console.error('error from the decorator', e)
          }
        }
      }
    }
    
    class Example {
      @errorHandler
      addComponent() {
        throw new Error('Error')
      }
    }
    
    new Example().addComponent();

    【讨论】:

    • 谢谢,如果我使用异步函数也会这样吗?
    • 更新代码以使用异步和非异步函数
    • 酷,在我在我的函数中使用它之前,一切看起来都很好,但是为什么当我在我的类方法中访问它时我得到一个例外,我应该以不同的方式处理我的方法因为装饰器?
    • 嗯,是的,我想我可能对类函数有问题。我已经更新了代码。现在是async function(...args) { 而不是async (...args) => {,所以它应该为类方法正确设置this
    • 哦,最后感谢伙计,我最终验证了构造函数名称而不是“typeof”——这让我可以选择以不同的方式处理异步函数和常规函数;还有箭头函数的这个问题,我遇到过很多次了,到现在都觉得不去检查这个还是很惊讶。
    猜你喜欢
    • 2021-12-15
    • 2015-10-23
    • 2023-01-04
    • 2023-03-04
    • 2016-12-14
    • 2021-12-23
    • 2016-02-21
    • 1970-01-01
    相关资源
    最近更新 更多