Lesson 03-Axios Response Handling

Response Structure

{
  // `data` is the response provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` are the server response headers
  // All header names are lowercase and can be accessed using bracket notation
  // e.g., `response.headers['content-type']`
  headers: {},

  // `config` is the configuration used for the axios request
  config: {},

  // `request` is the request that generated this response
  // In Node.js, it is the last ClientRequest instance (for redirects)
  // In browsers, it is an XMLHttpRequest instance
  request: {}
}

Parsing JSON Responses

Axios automatically parses JSON responses by default. If the server returns a JSON-formatted response body, Axios converts it into a JavaScript object, eliminating the need to manually call JSON.parse().

Example:

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data); // Directly access the data
  })
  .catch(error => {
    console.error(error);
  });

Advanced Error and Exception Handling

Error handling is a critical aspect of network requests. Axios provides several ways to manage errors and exceptions:

  • Response Status Code Handling: Check error.response.status to identify the error type.
  • Custom Error Handling: Implement custom logic in .catch().
  • Using validateStatus Configuration: Customize which HTTP status codes are considered successful by configuring the validateStatus function.

Example:

axios.get('https://api.example.com/data', {
  validateStatus: status => status < 500 // Custom status code validation
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (error.response) {
      console.error('Server responded with a status of:', error.response.status);
    } else if (error.request) {
      console.error('No response received:', error.request);
    } else {
      console.error('Error setting up the request:', error.message);
    }
    console.error('Error config:', error.config);
  });

Custom Response Interceptors

Response interceptors allow you to modify or handle response data, including error handling, before the request completes. They are useful for unified error handling, logging, or transforming response data.

Example:

axios.interceptors.response.use(
  response => {
    // Modify response data
    return response;
  },
  error => {
    // Handle response errors
    if (error.response.status === 401) {
      // Redirect to login page for unauthorized status
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

In custom response interceptors, you can:

  • Return the response object to pass it to the next interceptor or .then() handler.
  • Return a new Promise for asynchronous operations.
  • Throw an error or return Promise.reject(error) to trigger error handling in .catch().
Share your love