Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 553
Jacob Goh Avatar asked Jan 17 '18 10:01

Jacob Goh


People also ask

Does Axios throw 404?

When using an axios instance for a GET request, 404 response status causes a request error and rejected promise. Using axios directly for the same request results in no request errors and Promise is successful.

Why does Axios throw error on 400?

By default, the axios HTTP library throws an error anytime the destination server responds with a 4XX / 5XX error (for example, a 400 Bad Request ). Since axios raises an error, your workflow will stop at this step. See the axios docs for more information.

How do you handle Axios promises?

Promises can be handled in two ways using modern JS - the async/await syntax, which was shown above, as well as . then() and . catch() methods.


2 Answers

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   } })(); 
like image 187
T.J. Crowder Avatar answered Oct 01 '22 09:10

T.J. Crowder


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

like image 41
Oliver Avatar answered Oct 01 '22 09:10

Oliver