Following tryCatch decorator is unable to catch the error.
const TryCatchWrapper = (target, key, descriptor) => {
const fn = descriptor.value;
descriptor.value = (...args) => {
try {
fn.apply(this, args);
} catch (error) {
console.log('Entered Catch----->');
const [,, next] = args;
next(error);
}
};
};
Trying to use in the following class-
class CustomerDetails {
@TryCatchWrapper
async getCustomerSummary(req, res, next) {
throw new Error('Whoops!!!');
}
}
Problem:- 'Entered Catch----->' never gets printed.
Following tryCatch decorator is unable to catch the error.
const TryCatchWrapper = (target, key, descriptor) => {
const fn = descriptor.value;
descriptor.value = (...args) => {
try {
fn.apply(this, args);
} catch (error) {
console.log('Entered Catch----->');
const [,, next] = args;
next(error);
}
};
};
Trying to use in the following class-
class CustomerDetails {
@TryCatchWrapper
async getCustomerSummary(req, res, next) {
throw new Error('Whoops!!!');
}
}
Problem:- 'Entered Catch----->' never gets printed.
Share Improve this question asked Nov 30, 2017 at 7:01 Let me seeLet me see 5,0949 gold badges39 silver badges49 bronze badges 1- Did you ever get this working? – jackdaw Commented Jul 30, 2018 at 13:55
2 Answers
Reset to default 8It's because getCustomerSummary
is an async
function. An async
function never throws; instead, it returns a promise that gets rejected. (Inside an async
function, when you use try
/catch
around await
, that gets turned into promise rejection handling. But in a non-async
function calling an async
function, that sugar isn't applied.)
You'll need to modify the decorator to look at the return value of the function and, if it's a promise, handle promise rejections.
Actually there is nothing wrong with your approach. You just forgot to await
for results from fn.apply
and set the descriptor.value
as async
function.
See the example here https://stackblitz./edit/typescript-dycwcg
const TryCatchWrapper = (target, key, descriptor) => {
const fn = descriptor.value;
descriptor.value = async (...args) => {
try {
await fn.apply(this, args);
} catch (error) {
console.log('Entered Catch----->');
const [,, next] = args;
next(error);
}
};
};