Axios получить статус ошибки

This may seem stupid, but I’m trying to get the error data when a request fails in Axios.

axios
  .get('foo.example')
  .then((response) => {})
  .catch((error) => {
    console.log(error); //Logs a string: Error: Request failed with status code 404
  });

Instead of the string, is it possible to get an object with perhaps the status code and content? For example:

Object = {status: 404, reason: 'Not found', body: '404 Not found'}

Stephen Ostermiller's user avatar

asked Aug 25, 2016 at 19:13

Sebastian Olsen's user avatar

Sebastian OlsenSebastian Olsen

10.3k9 gold badges46 silver badges93 bronze badges

What you see is the string returned by the toString method of the error object. (error is not a string.)

If a response has been received from the server, the error object will contain the response property:

axios.get('/foo')
  .catch(function (error) {
    if (error.response) {
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    }
  });

answered Aug 25, 2016 at 19:34

Nick Uraltsev's user avatar

Nick UraltsevNick Uraltsev

24.7k4 gold badges25 silver badges14 bronze badges

17

With TypeScript, it is easy to find what you want with the right type.

This makes everything easier because you can get all the properties of the type with autocomplete, so you can know the proper structure of your response and error.

import { AxiosResponse, AxiosError } from 'axios'

axios.get('foo.example')
  .then((response: AxiosResponse) => {
    // Handle response
  })
  .catch((reason: AxiosError) => {
    if (reason.response!.status === 400) {
      // Handle 400
    } else {
      // Handle else
    }
    console.log(reason.message)
  })

Also, you can pass a parameter to both types to tell what are you expecting inside response.data like so:

import { AxiosResponse, AxiosError } from 'axios'
axios.get('foo.example')
  .then((response: AxiosResponse<{user:{name:string}}>) => {
    // Handle response
  })
  .catch((reason: AxiosError<{additionalInfo:string}>) => {
    if (reason.response!.status === 400) {
      // Handle 400
    } else {
      // Handle else
    }
    console.log(reason.message)
  })

Stephen Ostermiller's user avatar

answered Sep 17, 2019 at 3:03

Yan QiDong's user avatar

3

As @Nick said, the results you see when you console.log a JavaScript Error object depend on the exact implementation of console.log, which varies and (imo) makes checking errors incredibly annoying.

If you’d like to see the full Error object and all the information it carries bypassing the toString() method, you could just use JSON.stringify:

axios.get('/foo')
  .catch(function (error) {
    console.log(JSON.stringify(error))
  });

answered Feb 14, 2017 at 9:17

danii's user avatar

daniidanii

5,5532 gold badges21 silver badges23 bronze badges

2

There is a new option called validateStatus in request config. You can use it to specify to not throw exceptions if status < 100 or status > 300 (default behavior). Example:

const {status} = axios.get('foo.example', {validateStatus: () => true})

Stephen Ostermiller's user avatar

answered Mar 31, 2020 at 12:44

Dmytro Naumenko's user avatar

You can use the spread operator (...) to force it into a new object like this:

axios.get('foo.example')
    .then((response) => {})
    .catch((error) => {
        console.log({...error})
})

Be aware: this will not be an instance of Error.

Stephen Ostermiller's user avatar

answered Jan 22, 2020 at 20:31

Moses Schwartz's user avatar

Moses SchwartzMoses Schwartz

2,8771 gold badge20 silver badges32 bronze badges

0

I am using this interceptors to get the error response.

const HttpClient = axios.create({
  baseURL: env.baseUrl,
});

HttpClient.interceptors.response.use((response) => {
  return response;
}, (error) => {
  return Promise.resolve({ error });
});

answered Dec 5, 2016 at 16:41

Tan's user avatar

TanTan

3423 silver badges11 bronze badges

2

In order to get the http status code returned from the server, you can add validateStatus: status => true to axios options:

axios({
    method: 'POST',
    url: 'http://localhost:3001/users/login',
    data: { username, password },
    validateStatus: () => true
}).then(res => {
    console.log(res.status);
});

This way, every http response resolves the promise returned from axios.

https://github.com/axios/axios#handling-errors

answered May 7, 2020 at 11:48

Emre Tapcı's user avatar

Emre TapcıEmre Tapcı

1,74317 silver badges16 bronze badges

Whole error can only be shown using error.response like that :

axios.get('url').catch((error) => {
      if (error.response) {
        console.log(error.response);
      }
    });

answered Jul 1, 2021 at 10:07

Manik Verma's user avatar

const handleSubmit = (e) => {
e.preventDefault();
// console.log(name);
setLoading(true);
createCategory({ name }, user.token)
  .then((res) => {
   // console.log("res",res);
    setLoading(false);
    setName("");
    toast.success(`"${res.data.name}" is created`);
    loadCategories();
  })
  .catch((err) => {
    console.log(err);
    setLoading(false);
    if (err.response.status === 400) toast.error(err.response.data);//explained in GD
  });

};

See the console log then you will understand clearly

enter image description here

answered Oct 7, 2022 at 4:08

Shakil- The Coding monster's user avatar

With Axios

    post('/stores', body).then((res) => {

        notifyInfo("Store Created Successfully")
        GetStore()
    }).catch(function (error) {

        if (error.status === 409) {
            notifyError("Duplicate Location ID, Please Add another one")
        } else {
            notifyError(error.data.detail)
        }

    })

answered Sep 3, 2021 at 5:43

Rumesh Madushanka's user avatar

Axios. get('foo.example')
.then((response) => {})
.catch((error) => {
    if(error. response){
       console.log(error. response. data)
       console.log(error. response. status);

      }
})

Stephen Ostermiller's user avatar

answered Jan 14, 2021 at 5:59

Vignesh's user avatar

VigneshVignesh

1741 silver badge5 bronze badges

3

It’s indeed pretty weird that fetching only error does not return an object. While returning error.response gives you access to most feedback stuff you need.

I ended up using this:

axios.get(...).catch( error => { return Promise.reject(error.response.data.error); });

Which gives strictly the stuff I need: status code (404) and the text-message of the error.

answered Apr 27, 2021 at 12:14

Bogdan Antone's user avatar

You can put the error into an object and log the object, like this:

axios.get('foo.example')
    .then((response) => {})
    .catch((error) => {
        console.log({error}) // this will log an empty object with an error property
    });

Stephen Ostermiller's user avatar

answered Jan 22, 2020 at 21:29

Mendy's user avatar

MendyMendy

7,6325 gold badges28 silver badges42 bronze badges

An Axios Error has a lot of information, but if you do a regular console.log(error) you would just get a ‘string message’ generic error like: «Error: Request failed with status code XXX»

A Typescript solution to handle Axios Error and other errors.

axios.get('foo.example')
    .then((response) => {//...})
    .catch (error: any) {
        let errorResponse: any;

        // it is an AxiosError
        if (error?.isAxiosError) {
            const axiosError = error as AxiosError;
            errorResponse = axiosError.response; //all the info here
        } else {
            errorResponse = error; // it is not an AxiosError
        }

        console.log(errorResponse);
        throw errorResponse;
    }

answered May 15 at 13:44

Juanma Menendez's user avatar

Juanma MenendezJuanma Menendez

17.3k7 gold badges59 silver badges56 bronze badges

It’s my code: Work for me

 var jsonData = request.body;
    var jsonParsed = JSON.parse(JSON.stringify(jsonData));

    // message_body = {
    //   "phone": "5511995001920",
    //   "body": "WhatsApp API on chat-api.com works good"
    // }

    axios.post(whatsapp_url, jsonParsed,validateStatus = true)
    .then((res) => {
      // console.log(`statusCode: ${res.statusCode}`)

            console.log(res.data)
        console.log(res.status);

        // var jsonData = res.body;
        // var jsonParsed = JSON.parse(JSON.stringify(jsonData));

        response.json("ok")
    })
    .catch((error) => {
      console.error(error)
        response.json("error")
    })

answered Jul 4, 2020 at 12:17

Rodrigo Grossi's user avatar

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

Using the validateStatus config option, you can define HTTP code(s) that should throw an error.

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Resolve only if the status code is less than 500
  }
})

Using toJSON you get an object with more information about the HTTP error.

axios.get('/user/12345')
  .catch(function (error) {
    console.log(error.toJSON());
  });

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.

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:

  • How to access the Value of a Promise in JavaScript
  • Get the Stack Trace from an Error in JavaScript
  • Get the filename without the path using JavaScript

I’m Edward Anderson. My current job is as a programmer. I’m majoring in information technology and 5 years of programming expertise. Python, C, C++, Javascript, Java, HTML, CSS, and R are my strong suits. Let me know if you have any questions about these programming languages.


Name of the university: HCMUT
Major: CS
Programming Languages: Python, C, C++, Javascript, Java, HTML, CSS, R

When making HTTP requests using the Axios library, it’s possible to encounter errors such as 4xx or 5xx status codes, indicating a client or server error respectively. In order to handle these errors and retrieve the specific status code, it’s necessary to catch the error and extract the code from the error response.

Method 1: Use catch block to retrieve status code

To retrieve the status code from an HTTP error in Axios, you can use the catch block to handle the error and extract the status code. Here’s an example code:

axios.get('/api/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

In the catch block, we check if the error has a response property. If it does, it means that the request was made and the server responded with a status code that falls out of the range of 2xx. We can then extract the status code from error.response.status.

If the error does not have a response property, it means that the request was made but no response was received. We can handle this case separately.

Finally, if something happened in setting up the request that triggered an error, we can catch it and log the error message.

This is just one of the many ways to retrieve the status code from an HTTP error in Axios. It’s important to handle errors properly in your code to provide a better user experience and prevent unexpected errors from crashing your application.

Method 2: Access status code from response object

To access the status code from an HTTP error in Axios, you can use the response object that is returned from the request. Here is an example code snippet that demonstrates how to do this:

axios.get('https://example.com/api/data')
  .then(response => {
    // Handle successful response
  })
  .catch(error => {
    if (error.response) {
      console.log(error.response.status);
    }
  });

In this example, we are making a GET request to https://example.com/api/data. If the request is successful, the then block will execute and we can handle the response data. However, if the request returns an error, the catch block will execute.

Within the catch block, we check if the error has a response property. If it does, that means the server responded with an error status code (e.g. 404 Not Found). We can then access the status code using error.response.status.

This is just one way to access the status code from an HTTP error in Axios. There are many other methods and properties available on the error and response objects, depending on your specific use case.

If you have been searching the web for some information about AXIOS error messages, and would like to understand how to use them, then you have come to the right place.

TLTR; Find the code snippets in the following section

If you search the web on this topic, all you can find is:

  • catching error body using axios post
  • Unable to catch the body of error
  • JS Axios – how to get response body in event of error?
  • How to see axios error response JSON in React

The list could have gone on and on, but they all ask for the sample simple question:

How can someone get the actual error information coming from a bad request made with AXIOS.

In this post we are going to provide information on “why” so many people ask for information, and “how” this information can be found.

Why so many people ask for this

If you have ever worked with an api, you perfectly know that request not always go to plan. You hope to always get a lovely response with a status of 200, but this does not always happens.

In many instances the status of our request may return some kind of error (400, 500), and when this happens we would like to be able to have a readable error message.

axios.get('EndpointWithAuthorizedError')
    .then((response) => {})
    .catch((error) => {
        console.log(error);
    })

Enter fullscreen mode

Exit fullscreen mode

Unfortunately if the above would ever fail with a meaningful error, we would still see this within our console, as the variable passed by the catch statement seem to be of type “string”.

Error: Request failed with status code 401

Enter fullscreen mode

Exit fullscreen mode

This is actually the main reason why so many people are “forced” to ask for help.

How can we process AXIOS error message

There is actually no magic when processing the error messages. In fact, the catch is in the fact that the variable received by the catch statement seem to be a string, but in reality it is not.

The AXIOS error message can actually return 3 different structure, depending from what kind of failure it has (crazy right… I thought that too).

Error in setting up the request

This error can happen if we have made an actual mistake in setting up the AXIOS request. It could be something with the data passed, or a configuration setting.

When this happen we can actually find the information we need by accessing the message parameter of the catch.

axios.get('wrongSetup')
    .then((response) => {})
    .catch((error) => {
        console.log(error.message);
    })

//or using destructuring
axios.get('wrongSetup')
    .then((response) => {})
    .catch(({message) => {
        console.log(message);
    })

Enter fullscreen mode

Exit fullscreen mode

No response – Network Error

This scenario will take place when our request had no response at all. This can happen when the URL is incorrect, or if the receiving server is down.

When this happen we can access more information about our request bu accessing the request parameter. This will return the actual “request” information.

axios.get('network error')
     .then((response) => {})
     .catch((error) => {
         console.log(error. request );
     })
//or using destructuring
 axios.get('network error')
     .then((response) => {})
     .catch(({ request ) => {
         console.log( request );
     })

Enter fullscreen mode

Exit fullscreen mode

Request returned with an error status

This is one of the most common, or more specifically the one type of “error” that need to be manage to make sure our web applications function properly.

There are hundreds of status code differently than 200 (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status), that would fit in this category. I am going to list below the most important:

  • 400: Bad request
  • 401: Unauthorized
  • 403: Forbidden
  • 404: Not Found
  • 500: Internal Server error
  • 502: Bad Gateway

When any of the above happen, we would like to know more about the request. In this case there are more information provided to us: data, status, header.

axios.get('errorStatus')
     .then((response) => {})
     .catch((error) => { 
         console.log(error.response.data);  
         console.log(error.response.status);  
         console.log(error.response.headers); 
     })

//or using destructuring
 axios.get('errorStatus')
     .then((response) => {})
     .catch(({ response }) => { 
         console.log(response.data);  
         console.log(response.status);  
         console.log(response.headers);  
     })

Enter fullscreen mode

Exit fullscreen mode

With the above code, we will be able to get all the information we need about the response to our request. These includes the status code, the header and last but not least the data that the server has sent with the request.

When using any kind of API, the data parameter is going to include essential information, usually used for development purposes, but at times also good to show to the end users.

I hope to have saved you some time, and please feel free to comment, or provide suggestion to improve this post and help future readers

Понравилась статья? Поделить с друзьями:
  • Axios повторить запрос при ошибке
  • Axios ошибка 403
  • Axios ошибка 401
  • Axios обработка ошибок сервера
  • Axios vuex обработка ошибок