Sobes.tech
Middle+

What ways are there to handle errors in Promise? Can try/catch be used?

sobes.tech AI

Answer from AI

In JavaScript, there are several ways to handle errors in Promises:

  1. The .catch() method — the most common way to handle errors:
fetch('url')
  .then(response => response.json())
  .catch(error => {
    console.error('Error:', error);
  });
  1. The second argument in .then(onFulfilled, onRejected) — you can pass an error handling function:
promise.then(
  result => { /* handle result */ },
  error => { /* handle error */ }
);
  1. Using async/await with try/catch:
async function fetchData() {
  try {
    const response = await fetch('url');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

Important: The try/catch block cannot be used directly around a promise.then() call to catch errors inside the promise. try/catch works with await or synchronous code. If you use try/catch without await, errors in promises will not be caught.

Summary:

  • To handle errors in promises, you can use .catch() or the second argument of .then().
  • For async/await, use try/catch.
  • You cannot use try/catch to handle errors in promises without await.
What ways are there to handle errors in Promise? Can… - sobes.tech