Table of Contents

Introduction to JavaScript Promise Error Handling

JavaScript Promises make asynchronous operations easier to organize, but an operation can fail for many reasons. A network request may be rejected, a server may return an error, a file may be unavailable, or application code may throw an exception while processing a result. JavaScript Promise error handling provides a consistent way to detect these failures and respond without allowing an unhandled rejection to disrupt the application.

A Promise represents the eventual result of an asynchronous operation. It can be pending, fulfilled, or rejected. A fulfilled Promise has a result value, while a rejected Promise has a reason that describes the failure. The main tools for handling Promise failures are catch(), the rejection callback of then(), and finally(). The async and await syntax also supports familiar try...catch blocks.

This tutorial explains how to catch rejected Promises, propagate errors through a chain, handle errors in asynchronous functions, distinguish expected failures from programming mistakes, and avoid common Promise error-handling problems.

Understanding Promise Rejection

A Promise is rejected when its operation cannot produce the expected result. You can reject a Promise explicitly with Promise.reject() or by calling the reject() function inside the Promise executor. An exception thrown inside the executor also rejects the Promise automatically.

const request = new Promise((resolve, reject) => {
  const hasConnection = false;

  if (hasConnection) {
    resolve("Data loaded successfully");
  } else {
    reject(new Error("Network connection failed"));
  }
});

request.catch((error) => {
  console.error(error.message);
});

In this example, the connection check fails, so the Promise is rejected with an Error object. The catch() method receives that rejection reason. Using an Error object is generally preferable to rejecting with a plain string because it provides a message and a stack trace that can help with debugging.

Rejection does not necessarily mean the entire application must stop. It means the asynchronous operation did not complete successfully. The code that consumes the Promise should decide whether to retry, show a message, use fallback data, or pass the error to another layer.

Handling Promise Errors with catch()

The catch() method is the most common way to handle a rejected Promise. It registers a rejection handler and returns a new Promise. The handler receives the rejection reason. If the handler returns a normal value, the Promise returned by catch() becomes fulfilled with that value. If it throws an error or returns a rejected Promise, the new Promise remains rejected.

const result = Promise.reject(new Error("Unable to load profile"));

result
  .catch((error) => {
    console.error("Request failed:", error.message);
    return { name: "Guest" };
  })
  .then((user) => {
    console.log(user.name); // Guest
  });

This example handles the failure and supplies fallback data. Because the error handler returns an object, the next then() receives that object as a successful value. This is called error recovery.

Use catch() near the point where you can make a meaningful decision about the failure. A UI component may display a message, while a data service may add context and rethrow the error so the calling component can decide what to do.

Using the Rejection Callback in then()

The then() method accepts up to two callbacks: a fulfillment callback and a rejection callback. The second callback runs when the Promise on which then() is called is rejected.

fetch("/api/users")
  .then(
    (response) => {
      if (!response.ok) {
        throw new Error(`HTTP error: ${response.status}`);
      }
      return response.json();
    },
    (error) => {
      console.error("Network-level failure:", error.message);
      throw error;
    }
  )
  .then((users) => {
    console.log(users);
  })
  .catch((error) => {
    console.error("Could not load users:", error.message);
  });

The second argument to then() handles rejection from the Promise immediately before it. It does not catch an exception thrown by the first fulfillment callback in the same then(). That is why a final catch() is useful: it can handle both a rejected source Promise and errors thrown by earlier fulfillment handlers in the chain.

For most application code, chaining then() for successful values and adding a catch() at the end is easier to read and maintain than passing a rejection callback to every then().

How Errors Propagate Through a Promise Chain

Promise chains pass values and errors from one step to the next. When a handler throws an exception, the Promise returned by that handler becomes rejected. The next rejection handler in the chain can catch it. If no rejection handler handles the error, the rejection continues through the chain.

getUser()
  .then((user) => {
    if (!user) {
      throw new Error("User was not found");
    }
    return getOrders(user.id);
  })
  .then((orders) => {
    return calculateTotal(orders);
  })
  .then((total) => {
    console.log("Order total:", total);
  })
  .catch((error) => {
    console.error("User or order processing failed:", error.message);
  });

If getUser() rejects, the later fulfillment handlers are skipped until a rejection handler is reached. The same behavior applies if a handler throws an exception or returns a rejected Promise. This propagation makes it possible to place one error handler after several related asynchronous steps.

A common mistake is to start a Promise inside a handler but forget to return it. Without the return statement, the outer chain does not wait for that inner operation, and its rejection may not reach the outer catch(). Return Promises from handlers whenever the next step depends on their result.

Throwing Errors to Reject a Promise

You can use the throw statement inside a Promise handler to reject the Promise returned by that handler. This is useful when an asynchronous operation technically succeeds but its result does not meet the application’s requirements.

function getProduct(product) {
  return Promise.resolve(product).then((item) => {
    if (!item || !item.id) {
      throw new Error("Invalid product data");
    }
    return item;
  });
}

getProduct({ name: "Keyboard" })
  .then((product) => console.log(product))
  .catch((error) => console.error(error.message));

The input Promise is fulfilled, but the validation handler throws an error because the product has no ID. The returned Promise is therefore rejected, and the following catch() handles it. This pattern is useful for validating API responses, checking permissions, and enforcing business rules.

Handling Errors with async and await

JavaScript’s async and await syntax provides another way to work with Promises. An async function always returns a Promise. When an awaited Promise rejects, the rejection behaves like an exception at the await expression. You can handle it with a normal try...catch block.

async function loadUser() {
  try {
    const response = await fetch("/api/user");

    if (!response.ok) {
      throw new Error(`Request failed with status ${response.status}`);
    }

    const user = await response.json();
    console.log(user);
    return user;
  } catch (error) {
    console.error("Unable to load user:", error.message);
    return null;
  }
}

loadUser();

The try block contains the operations that may fail. If fetch() rejects, JSON parsing throws, or the code explicitly throws an Error, execution moves to the catch block. Returning null is one possible recovery strategy, but choose a fallback that makes sense for your application.

Be aware that fetch() does not reject just because a server responds with an HTTP status such as 404 or 500. It normally fulfills with a Response object. Check response.ok or response.status and throw an error when an unsuccessful HTTP response should be treated as a failure.

Handling Errors in async Functions Called by Other Functions

An error caught inside an async function does not reach its caller if the function handles it and returns a normal value. If the caller needs to handle the failure, rethrow the error or allow it to propagate by not catching it locally.

async function fetchSettings() {
  const response = await fetch("/api/settings");

  if (!response.ok) {
    throw new Error("Settings request failed");
  }

  return response.json();
}

async function initializeApp() {
  try {
    const settings = await fetchSettings();
    applySettings(settings);
  } catch (error) {
    showErrorMessage(error.message);
  }
}

initializeApp();

Here, fetchSettings() focuses on retrieving settings and throws when the request is unsuccessful. initializeApp() decides how the user interface should respond. Keeping these responsibilities separate makes functions easier to test and reuse.

Using finally() for Cleanup

The finally() method runs after a Promise settles, whether it is fulfilled or rejected. It is commonly used for cleanup tasks such as hiding a loading indicator, releasing a resource, or resetting a temporary state.

showLoading();

fetch("/api/products")
  .then((response) => {
    if (!response.ok) {
      throw new Error("Products could not be loaded");
    }
    return response.json();
  })
  .then((products) => {
    renderProducts(products);
  })
  .catch((error) => {
    showErrorMessage(error.message);
  })
  .finally(() => {
    hideLoading();
  });

The callback passed to finally() does not receive the fulfillment value or rejection reason. Normally, its return value does not replace the original result. However, if the callback itself throws an error or returns a rejected Promise, it can change the outcome of the Promise returned by finally(). Keep cleanup callbacks simple and avoid introducing new failures inside them.

Creating Custom Error Objects

For larger applications, custom Error classes can make failures easier to identify. A custom class can include a descriptive name, an error code, or additional information that helps the application decide how to respond.

class ApiError extends Error {
  constructor(message, status) {
    super(message);
    this.name = "ApiError";
    this.status = status;
  }
}

async function getArticles() {
  const response = await fetch("/api/articles");

  if (!response.ok) {
    throw new ApiError("Unable to retrieve articles", response.status);
  }

  return response.json();
}

getArticles().catch((error) => {
  if (error instanceof ApiError) {
    console.error("API status:", error.status);
  }
  console.error(error.message);
});

Custom errors are particularly helpful when different failure types need different handling. For example, an authentication error may redirect a user to a sign-in page, while a validation error may be displayed beside a form field. Avoid creating a custom class for every minor condition; use a small set of meaningful error types.

Handling Multiple Promises and Their Errors

When an application starts several asynchronous operations, the Promise static methods determine how their results and failures are handled. Promise.all() rejects as soon as one input Promise rejects. This is appropriate when every operation must succeed for the combined result to be useful.

Promise.all([
  fetch("/api/profile"),
  fetch("/api/notifications"),
  fetch("/api/preferences")
])
  .then(([profile, notifications, preferences]) => {
    console.log(profile, notifications, preferences);
  })
  .catch((error) => {
    console.error("At least one request failed:", error.message);
  });

If you need the outcome of every operation, including individual failures, use Promise.allSettled(). It fulfills with an array of result objects. Each object has a status property that is either fulfilled or rejected. Fulfilled entries contain value; rejected entries contain reason.

const results = await Promise.allSettled([
  loadProfile(),
  loadMessages(),
  loadPreferences()
]);

results.forEach((result) => {
  if (result.status === "fulfilled") {
    console.log("Loaded:", result.value);
  } else {
    console.error("Failed:", result.reason);
  }
});

Choose Promise.all() when one failure should reject the combined operation. Choose Promise.allSettled() when each operation can be evaluated independently and partial results are useful.

Preventing Unhandled Promise Rejections

An unhandled rejection occurs when a Promise rejects and no rejection handler is attached in time. Browsers may report an unhandled Promise rejection in the console, and Node.js can report or terminate on unhandled rejections depending on its version and runtime configuration. Do not rely on the environment’s default behavior as your error strategy.

// Not handled
fetch("/api/data");

// Handled with catch()
fetch("/api/data")
  .then((response) => response.json())
  .catch((error) => {
    console.error("Data request failed:", error);
  });

// Handled with async/await
async function loadData() {
  try {
    const response = await fetch("/api/data");
    return await response.json();
  } catch (error) {
    console.error("Data request failed:", error);
    return null;
  }
}

Attach a rejection handler to Promises that may fail. Also remember that calling an async function creates a Promise. If you call it without awaiting it or attaching catch(), its rejection may become unhandled. At application boundaries, such as event handlers, background jobs, and startup routines, make sure asynchronous failures are observed.