Jacob Goh
Jacob Goh

Reputation: 20845

Axios. How to get error response even when api return 404 error, in try catch finally

for e.g.

(async() => {
  let apiRes = null;
  try {
    apiRes = await axios.get('https://silex.edgeprop.my/api/v1/a');
  } catch (err) {
    console.error(err);
  } finally {
    console.log(apiRes);
  }
})();

in finally, apiRes will return null.

Even when the api get a 404 response, there is still useful information in the response that I would like to use.

How can I use the error response in finally when axios throws error.

https://jsfiddle.net/jacobgoh101/fdvnsg6u/1/

Upvotes: 89

Views: 156695

Answers (4)

ESP32
ESP32

Reputation: 8723

Concerning the accepted solution { validateStatus: false }:

It's also important to note that you will still see the same error message on the line with axios.get(....)

However the code proceeds in the ".then(...)" part. This is a strange behaviour which cost me a lot of testing time, because I thought that the setting had no affect.

Upvotes: 0

You can treate the status code:

exemple using Ts:

let conf: AxiosRequestConfig = {};

    conf.validateStatus = (status: number) => {
        
        return (status >= 200 && status < 300) || status == 404
    }

    let response = await req.get(url, conf);

Upvotes: 5

Oliver
Oliver

Reputation: 1053

According to the AXIOS documentation (here: https://github.com/axios/axios) you can pass validateStatus: false in the config object to any axios request.

e.g.

axios.get(url, { validateStatus: false })
axios.post(url, postBody, { validateStatus: false })

You can also pass a function like this: validateStatus: (status) => status === 200 According to the docs the default behaviour is function that returns true if (200 <= status < 300).

Upvotes: 93

T.J. Crowder
T.J. Crowder

Reputation: 1075537

According to the documentation, the full response is available as a response property on the error.

So I'd use that information in the catch block:

(async() => {
  let apiRes = null;
  try {
    apiRes = await axios.get('https://silex.edgeprop.my/api/v1/a');
  } catch (err) {
    console.error("Error response:");
    console.error(err.response.data);    // ***
    console.error(err.response.status);  // ***
    console.error(err.response.headers); // ***
  } finally {
    console.log(apiRes);
  }
})();

Updated Fiddle

But if you want it in finally instead, just save it to a variable you can use there:

(async() => {
  let apiRes = null;
  try {
    apiRes = await axios.get('https://silex.edgeprop.my/api/v1/a');
  } catch (err) {
    apiRes = err.response;
  } finally {
    console.log(apiRes); // Could be success or error
  }
})();

Upvotes: 127

Related Questions