乐闻世界logo
搜索文章和话题

How to get response data in error from AJAX response?

1个答案

1

When handling AJAX requests, correctly processing error responses is crucial. The primary goal is to ensure users receive clear error messages and developers can obtain sufficient information for debugging. Here, I'll demonstrate how to retrieve error response data from AJAX responses using an example.

First, let's assume we're using the widely adopted fetch API in JavaScript to send AJAX requests. When using fetch to send requests, it returns a Promise. fetch rejects this Promise in cases of network errors or failed request initiation, but resolves it if the server responds (even with a 4xx or 5xx HTTP status code).

This means that even for an HTTP error response, fetch treats it as a successful response. Therefore, we need to manually check the HTTP status code when handling the fetch response to determine if it's truly successful. Here's an example:

javascript
fetch('https://api.example.com/data', { method: 'GET' }) .then(response => { if (!response.ok) { // Check if HTTP status code falls within the 200-299 range return response.json().then(errorData => { // Handle error response data from the server console.error('Error occurred:', errorData); throw errorData; // Throw error data for subsequent catch handling }); } return response.json(); }) .then(data => { console.log('Received data:', data); // Handling successful response }) .catch(error => { console.error('Failed to fetch data:', error); // Capture errors });

In this example:

  1. We send a GET request to https://api.example.com/data.
  2. When the response is received, we first check the response.ok property, which is a boolean indicating whether the status code falls within the 200-299 range.
  3. If response.ok is false, it indicates an error status code. We read the response body using response.json(), which typically contains specific error information.
  4. After parsing the error data, we can use this information for error handling, such as logging errors or displaying error messages to users.
  5. If the status code is successful, we similarly parse the successful data using response.json().
  6. Finally, use catch to capture any exceptions that occur during the request or response handling.

This handling pattern ensures we can correctly identify and process server error responses while also handling network or other errors that may occur during request initiation.

2024年7月26日 21:40 回复

你的答案