Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TryCatch Decorator not catching errors

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.

like image 660
Let me see Avatar asked Dec 08 '22 16:12

Let me see


1 Answers

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.

like image 65
T.J. Crowder Avatar answered Dec 10 '22 05:12

T.J. Crowder