[英]method babel decorators isn't executed
I'm using the babel 7 decorator plugin and I have a simple class and I want to decorate each method in a simple try catch wrapper. 我正在使用babel 7装饰器插件,并且我有一个简单的类,我想在一个简单的try catch包装器中装饰每个方法。
This is what've done: 这是做的:
const errorHandler = () => {
return (target, property, descriptor) => {
try {
return descriptor
} catch (e) {
console.error('error from the decorator', e)
}
}
}
In this is a sample of my class: 这是我班的一个例子:
class Example {
@errorHandler
addComponent() {
throw new Error('Error')
}
}
But when I'm executing the function it's not going throw the decorator before execution, only pre-evaluating when the class is being initialized. 但是,当我执行该函数时,它不会在执行之前抛出装饰器,而只是在初始化类时进行预评估。
any ideas? 有任何想法吗?
You are returning descriptor
, which is a function object and it gets executed by caller outside your try/catch
block. 您正在返回
descriptor
,它是一个函数对象,它由调用者在try/catch
块之外执行。 To intercept exception - you should execute descriptor
yourself. 要拦截异常-您应该自己执行
descriptor
。
The correct code is: 正确的代码是:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.