How To Get the Status Code of an Axios HTTP Error in JavaScript

Get the Status Code of an Axios HTTP Error in JavaScript

You can have two different ways of achieving the goal, by using the .then() and catch() method or using the async() and await() function. Let’s learn how to get the status code of an Axios HTTP Error in JavaScript.

Handling Errors With Axios

Axios is a Javascript framework that makes use of the Promise API to build HTTP requests using either XMLHttpRequests in the browser or HTTP in the Node.js runtime. These requests can use the more recent async/await syntax; the .then() utilities for promise chaining; and the .catch() mechanism for error management because they are promises.

import axios from 'axios';
try {
    let res = await axios.get('/my-api-route');

    // Work with the response...
} catch (err) {
    // Handle error
    console.log(err);
}

When performing any HTTP requests, it’s crucial to understand how to handle problems with Axios. Because there are instances when the resource you’re accessing may not be available or may return other unexpected issues. Although we’ll demonstrate the .then()/.catch() technique, async/await is the most common syntax.

Then and Catch

The async/await syntax, which we introduced above, as well as the .then() and .catch() function, are two ways that can handle promises in the current JS (). You should note that while both of these methods are capable of producing the same functionality. async/await is advantageous method because it needs less boilerplate code and can handle longer promise chains.

To accomplish the same goal using the then/catch technique, follow these steps:

import axios from 'axios';
axios.get('/my-api-route')
    .then(res => {
        // Work with the response...
    }).catch(err => {
        // Handle error
        console.log(err);
    });

Similar to the async/await syntax, the err and res are both present.

Get the Status Code of an Axios HTTP Error in JavaScript

To obtain the status code from an HTTP error response, just use the status field on the error.response instance, for example, error.response.status. The status code supplied by the server in reaction to the client’s request is returned by the error.response object’s status attribute. We’ll present the .then()/.catch() technique, and also the method using await/async.

Method 1: Using .then()/.catch() function

To get the status code of the error, we caught the error in a catch block and accessed the status property on the error.response object.

Below is an illustration of how to get the status code of an Axios HTTP Error using promise.then() and promise.catch() instead of async/await.

import axios from 'axios';
axios.get('/not/exist').then((response) => {
    console.log('Working well.');
}).catch((error) => {
    if (err.response)
        console.log(err.response.status);
})

An error code 404 is expected to be returned when we sought a route that didn’t exist.

Syntax:

promise.then(success).catch(error);

Parameter:

  • success: success() function would be called on fulfillment
  • error: error() function would be called if there is a failure

Output:

404

Method 2: Using async keyword

This is how to accomplish the same goal by incorporating the async/await technique within try/catch statement:

Syntax:

async function functionname(param0) {
//  your codes
}

Parameter:

  • functionname: The name of the function.
  • param0: The parameter’s name you want to pass to the function.

For instance, you can use the following code to get the status code of an Axios HTTP Error:

async function functioname() {
  try {
  await axios.get('/not/exist');
    console.log("Working well");
  } catch (err) {
    if (err.response) {
      let statuscode = err.response.status;
      console.log(statuscode);
}
   }
}

Output:

404

Summary

We have explained how to handle errors and problems with Axios in this post and how to get the status code of an Axios HTTP error in JavaScript. This is crucial in order to avoid always delivering a general error message, giving 404 errors, or suggesting network issues to users of your application or website.

Maybe you are interested:

Leave a Reply

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