tom
tom

Reputation: 449

How to catch the exception in the right way? [beginner]

There is the following function, which doesn't catch MyException.

const myFunction = () => async (req, res, next) => {
  try {
    myHTTPRequest().then(async (response) => {
      if (response.data.results.length != 1) {
        throw new MyException('MyError');
      }
      res.end('All good');
    })
    .catch((error) => {
      throw error; //Doesn't work
    });
  } catch (error) {
    console.log('This block should catch MyException, but it doesn't');
    next(error);
  }
};

Instead, the application writes following error message into the console

(node:45746) UnhandledPromiseRejectionWarning
(node:45746) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:45746) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

The question is, how does the code need to be adjusted to catch MyException in the expected Catch-Block?

Upvotes: 1

Views: 30

Answers (1)

Marcos Casagrande
Marcos Casagrande

Reputation: 40374

The issue is that you're mixing .then/.catch with try/catch.

If you want the code to enter the try/catch in an async function, you have to use the await keyword on the Promise.

You can drop the .catch since it's doing nothing, you're throwing again the error, and that's causing the UnhandledPromiseRejectionWarning

const myFunction = () => (req, res, next) => {
  try {
    const response = await myHTTPRequest();

    if (response.data.results.length != 1) {
      throw new MyException('MyError');
    }
    res.end('All good');

  } catch (error) {
    next(error);
  }
};

Using .then/catch without async/await the code would be:

const myFunction = () => (req, res, next) => {

    myHTTPRequest().then((response) => {
      if (response.data.results.length != 1) {
        throw new MyException('MyError');
      }
      res.end('All good');
    })
    .catch((error) => {
      throw error;
       // It makes no sense to throw again in here
       // But I'm showing you how to handle it if you do
    })
    .catch(error => {
        next(error);
    })
};

Of course the double .catch doesn't make sense, and you should remove it, leaving a single one:

const myFunction = () => (req, res, next) => {

    myHTTPRequest().then((response) => {
      if (response.data.results.length != 1) {
        throw new MyException('MyError');
      }
      res.end('All good');
    })
    .catch(error => {
        next(error);
    })
};

Upvotes: 4

Related Questions