![](/img/trans.png)
[英]Babel-Standalone Error : Inline Babel script: Support for the experimental syntax 'decorators-legacy' isn't currently enabled (14:1):
[英]method babel decorators isn't executed
我正在使用babel 7裝飾器插件,並且我有一個簡單的類,我想在一個簡單的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')
}
}
但是,當我執行該函數時,它不會在執行之前拋出裝飾器,而只是在初始化類時進行預評估。
有任何想法嗎?
您正在返回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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.