Skip to content

Instantly share code, notes, and snippets.

@fgilio
Last active August 15, 2024 01:45
Show Gist options
  • Save fgilio/230ccd514e9381fafa51608fcf137253 to your computer and use it in GitHub Desktop.
Save fgilio/230ccd514e9381fafa51608fcf137253 to your computer and use it in GitHub Desktop.
Catch request errors with Axios
/*
* Handling Errors using async/await
* Has to be used inside an async function
*/
try {
const response = await axios.get('https://your.site/api/v1/bla/ble/bli');
// Success 🎉
console.log(response);
} catch (error) {
// 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 and triggered an Error
console.log('Error', error.message);
}
console.log(error);
}
/*
* Handling Errors using promises
*/
axios.get('https://your.site/api/v1/bla/ble/bli')
.then((response) => {
// Success 🎉
console.log(response);
})
.catch((error) => {
// 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 and triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
@iradupat
Copy link

thank you very much

@Somesa
Copy link

Somesa commented Jun 8, 2020

good guy

@AdelinaUwU
Copy link

What is the best way in conjunction with rest api + react js? You forgot to write about interceptors, it seems they are better suited for processing since they allow you to write less code

@fgilio
Copy link
Author

fgilio commented Jun 15, 2020

What is the best way in conjunction with rest api + react js? You forgot to write about interceptors, it seems they are better suited for processing since they allow you to write less code

Do you have any example on the interceptors?

@AkshaySeth94
Copy link

For axios version-0.19.0 below code worked after hours of struggling with async await.Not sure about other versions though!

catch(error){
console.log(error.response.data.error)
}
Hope that helps!

@jimmybatuhan
Copy link

Kudos to you sir!

@lestgabo
Copy link

lestgabo commented Aug 17, 2020

For axios version-0.19.0 below code worked after hours of struggling with async await.Not sure about other versions though!

catch(error){
console.log(error.response.data.error)
}
Hope that helps!

Thanks this one helped!
But it does depend on what the backend returned. Obviously it should be error, but sometimes message.
My backend response used message so my response was:

catch (error) {
            console.log(error.response.data.message);
        }

@chrisloughnane
Copy link

cheers.

@afrontend
Copy link

Thank you!

@Avallos
Copy link

Avallos commented Nov 17, 2020

thanks man!

@hardik-jpm
Copy link

Thanks a lot!

@eiberham
Copy link

Thank u !

@farhankassam2
Copy link

farhankassam2 commented Feb 2, 2021

Hi there, I was having an issue earlier today whereby catching of AxiosErrors was not happening correctly using a try{}catch{} block but when I used the .then(...).catch(...) method, it was working perfectly fine and would throw an error I could play around with. With the former, I could not use the error response as it was returning undefined to me, and thus, show an undefined error message to the UI.

Does the author or anybody happen to know why this is the case? I am using TS with React Native and was running this on an iOS x simulator when I experienced this. Following are other versions of the software tools I am using:

  • react-native: ^0.63.3
  • react: ^16.14.0
  • cocoapods: cocoapods-1.8.4
  • node: v12.14.1
  • npm: 6.13.4
  • Xcode: 11.4
  • macOS: Catalina 10.15.5
  • ruby: ruby-2.6.3
  • react-native-cli: 2.0.1

Any help will be greatly appreciated.
Thanks!

@fgilio
Copy link
Author

fgilio commented Feb 3, 2021

Hi @farhankassam2! I've never used TS and React Native, but I'd be very interested in knowing what was the issue

@valtermoore
Copy link

Perfect !!

@rubensflinco
Copy link

:D

@fgilio
Copy link
Author

fgilio commented Apr 28, 2021

:D

@farhankassam2
Copy link

Hi @farhankassam2! I've never used TS and React Native, but I'd be very interested in knowing what was the issue

I think I fixed the issue. It seems like catching of errors using a try{}catch{} blocked wrapped around an API server call using axios does correctly catch error messages thrown from the server API call. Only issue is that if the error message is undefined or an empty string, the try{}catch{}block will not catch it.

I hope that clarifies it @fgilio?

@fgilio
Copy link
Author

fgilio commented Apr 29, 2021

I guess, yes. Is the server returning a 2xx status code even if there are errors? According to axios, any status code outside the range of 2xx should trigger the error

@sijucm
Copy link

sijucm commented Sep 9, 2021

I find it hard that I cannot get the request headers from the error object. If I try console.log(error.request.header) or _header I get nothing. When I print error.request I do get a lot of junk, but somehow I miss how to get to the header that was used. I will eventually get it I'm sure but the fact that it is so hard makes me wonder what were people thinking. It is so normal to log the header when the request fails so that the error can be reported.

@fgilio
Copy link
Author

fgilio commented Sep 11, 2021

I find it hard that I cannot get the request headers from the error object. If I try console.log(error.request.header) or _header I get nothing. When I print error.request I do get a lot of junk, but somehow I miss how to get to the header that was used. I will eventually get it I'm sure but the fact that it is so hard makes me wonder what were people thinking. It is so normal to log the header when the request fails so that the error can be reported.

Hmm yep, that's interesting. You're trying to get the headers from the request and not the failed response, right.

@alexisselorm
Copy link

Thanks a lot.!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment