Reputation: 1687
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?
Upvotes: 0
Views: 125
Reputation: 2502
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();
Upvotes: 2