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.
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. To intercept exception - you should execute descriptor
yourself.
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.