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

4

82

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/

Sabu answered 17/1, 2018 at 10:30 Comment(3)
Pesumably the useful info you're talking about is in err? I can't see why you want it in the finally rather than the catch, but if you do, simply save it in the catch to a variable you can access in the finally.Interpretation
@T.J.Crowder the error in catch doesn't contain the api response. if I can get around this then your method would work !Sabu
Yes, it does. (I just browsed the documentation.)Interpretation
I
122

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
  }
})();
Interpretation answered 17/1, 2018 at 10:42 Comment(1)
You can also see the err type definition here to find other useful data :)Latonya
O
86

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).

Oscillatory answered 14/12, 2018 at 12:7 Comment(4)
Thanks! used this as an option const options = { method: 'GET', headers: { 'Accept': 'application/json'}, url: 'url, validateStatus: false };Robers
Thank you, I think that try catch is ugly and over blows the code base. This is solving it...Opportunism
Can't believe how much time I spent trying to figure out why I was getting 404. This simple fix was all I needed.Mastaba
Great! My Axios instance ignored errors with a 404 status by default. It just threw an error to the console, ignored the rest of the code, and even disregarded the code after the await in an async function. That helped, thanks!Moxley
V
5

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);
Vertu answered 24/1, 2022 at 19:47 Comment(0)
S
0

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.

Swift answered 13/9, 2023 at 9:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.