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 yourtry/catch
block. To intercept exception - you should executedescriptor
yourself.The correct code is: