Home >Web Front-end >JS Tutorial >How Can You Gracefully Handle Fetch Errors Based on HTTP Status Codes?

How Can You Gracefully Handle Fetch Errors Based on HTTP Status Codes?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-10 02:13:02595browse

How Can You Gracefully Handle Fetch Errors Based on HTTP Status Codes?

Capturing Fetch Errors with Response Status

You're leveraging the fetch() API with Redux and the redux-promise-middleware library. Within your code snippet, you're attempting to check the response status and handle any errors. However, you're encountering an issue where the promise isn't getting rejected.

Understanding Fetch Promise Rejections

Fetch promises are unique in that they only reject due to network errors. Responses with status codes like 4xx (client errors) and 5xx (server errors) are considered non-network errors. Consequently, they won't trigger a rejection.

Resolving the Issue

To overcome this limitation and handle status-related errors, you need to manually throw an error:

fetch(url)
  .then((response) => {
    if (response.ok) {
      return response.json();
    }
    throw new Error('Something went wrong');
  })
  .then((responseJson) => {
    // Handle the data
  })
  .catch((error) => {
    // Handle the error
  });

This code snippet verifies the response status (response.ok). If it's not OK, it throws an error that triggers the Promise#catch() handler. This allows you to gracefully handle errors based on HTTP status codes.

The above is the detailed content of How Can You Gracefully Handle Fetch Errors Based on HTTP Status Codes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn