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.
It'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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With