Sobes.tech
Middle+

How to handle the rejected state of a promise using .then() and .catch()? How to understand in which .then() the error occurred and handle it separately?

sobes.tech AI

Answer from AI

To handle a rejected state of a promise, you can use both .then() and .catch().

  • .then(onFulfilled, onRejected) — the second argument handles the error.
  • .catch(onRejected) — handles the error if it occurred in any previous .then().

To understand exactly in which .then() the error occurred, you can split the chain and add error handlers after each .then(). For example:

promise
  .then(result => {
    // process result
    return nextStep(result);
  })
  .catch(error => {
    console.error('Error in first then:', error);
    throw error; // propagate the error further
  })
  .then(nextResult => {
    // next step
  })
  .catch(error => {
    console.error('Error in second then:', error);
  });

This approach allows you to localize error handling and understand where exactly the error occurred.

If you use only one .catch() at the end, it will catch errors from any .then(), but it won't provide information about the specific location of the error.

How to handle the rejected state of a promise using… - sobes.tech