Handling HTTP Errors in Axios

Understanding and Accessing Error Details in Axios

Axios is a popular JavaScript library for making HTTP requests. When these requests fail, it’s crucial to handle the errors gracefully and extract useful information about what went wrong. This tutorial will guide you through accessing error details, including the HTTP status code, within your Axios error handling.

Why Error Handling Matters

Robust error handling improves the user experience and helps you debug issues more effectively. Instead of just crashing or displaying a generic error message, you can pinpoint the source of the problem – whether it’s a network issue, a server error, or an invalid request.

The Structure of Axios Errors

When an Axios request fails, the catch block receives an error object. This object isn’t a simple string; it’s a more complex structure that can contain valuable information. However, directly logging this object (e.g., console.log(error)) may not always reveal the full details due to how the console.log function handles Error objects.

Accessing the HTTP Status Code

The most common piece of information you’ll need is the HTTP status code (e.g., 404 Not Found, 500 Internal Server Error). Here’s how to access it:

  1. Check for a Response: The error object might contain a response property if the server did respond with an error. This is the key to accessing status codes and other response details.

  2. Access error.response.status: If error.response exists, you can access the HTTP status code using error.response.status.

Here’s an example:

axios.get('/foo')
  .catch(function (error) {
    if (error.response) {
      console.log("Error Status:", error.response.status);
      console.log("Error Data:", error.response.data); // Access the response body
      console.log("Error Headers:", error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      console.log("No response received:", error.request);
    } else {
      // Something happened in setting up the request
      console.log("Error setting up the request:", error.message);
    }
  });

Explanation:

  • We check if error.response exists. This indicates that the server responded, but with an error.
  • If a response exists, we access error.response.status to get the HTTP status code.
  • We also access error.response.data to get the response body, which might contain a more detailed error message from the server.
  • The code also includes checks for scenarios where a response wasn’t received at all (error.request) or there was an error setting up the request (error.message).

Using TypeScript for Type Safety

If you’re using TypeScript, you can improve code clarity and maintainability by using type annotations:

import { AxiosResponse, AxiosError } from 'axios';

axios.get<any>('/foo') // Specify the expected response type
  .then((response: AxiosResponse<any>) => {
    // Handle response
  })
  .catch((reason: AxiosError) => {
    if (reason.response?.status === 400) {
      // Handle 400 error
    } else {
      // Handle other errors
    }
    console.log(reason.message);
  });

The ? in reason.response?.status is optional chaining, which prevents errors if reason.response is null or undefined.

Alternative Debugging Techniques

  • JSON.stringify(): To view the complete error object in a readable format, you can use JSON.stringify(error) in your console log.
  • validateStatus Configuration: Axios allows you to customize the behavior of error handling through the validateStatus configuration option. This allows you to define a function that determines whether a response should be considered an error based on the status code.

Best Practices

  • Check for error.response first: Always verify that error.response exists before attempting to access its properties.
  • Provide informative error messages: Display user-friendly error messages to help users understand what went wrong.
  • Log errors for debugging: Log detailed error information to your server logs for debugging and monitoring purposes.

Leave a Reply

Your email address will not be published. Required fields are marked *