Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
});
@nbkhope
Copy link

nbkhope commented Oct 18, 2017

Do you know how we could trigger a setup error that would go to the else statement, for testing purposes?

Loading

@Peace-N
Copy link

Peace-N commented Dec 14, 2017

Perfect was looking for this Gist !!!

Loading

@jplew
Copy link

jplew commented Jan 28, 2018

thanks friend, this was super useful. I eventually found the same thing in the official docs, but yours came up first: https://github.com/axios/axios#handling-errors

Loading

@rodhoward
Copy link

rodhoward commented Apr 11, 2018

This makes sense but I think I'm seeing a timing issue where I've hit the error condition (catch) before the response has come back. Using a break point in the code as well as millions of console.logs.

While the break point is on in catch error.response = undefined and network tab response is also empty. When I continue running network tab shows the error response, that I would like to display to the user, but the catch has already run its course at that stage.

Any workarounds suggestions?

SOLVED: 'Access-Control-Allow-Origin' headers were not set in the error case. Check for CORS errors on the console log if your getting this issue.

Loading

@rdemorais
Copy link

rdemorais commented Apr 15, 2018

Thanks, man

Loading

@stefmabo
Copy link

stefmabo commented Jun 24, 2018

Thanks :)

Loading

@behouba
Copy link

behouba commented Jul 12, 2018

great !!! thanks very helpful

Loading

@sooraj007ks
Copy link

sooraj007ks commented Jul 16, 2018

Thanks

Loading

@NotIntMan
Copy link

NotIntMan commented Aug 27, 2018

Awesome:) It was useful:)

Loading

@rerodrigues
Copy link

rerodrigues commented Sep 12, 2018

Really useful! Thanks!

Loading

@felipe-machado
Copy link

felipe-machado commented Oct 9, 2018

Just what I needed. Thanks!

Loading

@chriswaweru70
Copy link

chriswaweru70 commented Oct 14, 2018

`<script>

export default {
data () {
return {
id:'',
todo: '',
todos: []
}
},
methods: {
updateTodo () {
var _this = this

       req.callServer({
           data:{
 	             id: this.id,
                 text: this.todo,
                 completed: true
 	            },
                 meta_data:{},
                 command:"update_todo"
          }).then(response => {
                _this.fetchTodos ()
                _this.todo = ''
          }).catch(err => {
              console.log(err)
          })   
    },
    deleteTodo () {
        var _this = this

        req.callServer({
            data: {
 	          id: this.id,
           },
           meta_data:{},
           command:"delete_todo"
        }).then(response => {
             _this.fetchTodos ()
             _this.todo = ''
        }).catch(err => {
            console.log(err)
        })
    },
    createTodo () {
        var _this = this

        req.callServer({
            data:{
                text: this.todo
            },
            meta_data:{},
            command:"add_todo"
        }).then(response => {
            _this.fetchTodos ()
            _this.todo = ''
        }).catch(err => {
            console.log(err)
        })
    },
    fetchTodos (){
        var _this = this

        req.callServer({
            data:{},
            meta_data:{},
            command:"list_todo"
        }).then(response => {
            _this.todos = response.data.results
        }).catch(err => {
            console.log(err)
        })
    }
},
mounted (){
    this.fetchTodos ()
}

}
</script>`

Loading

@chriswaweru70
Copy link

chriswaweru70 commented Oct 14, 2018

#having trouble with thisc code too

Loading

@avks
Copy link

avks commented Mar 10, 2019

This is very helpful. THanks!

Loading

@clitorio
Copy link

clitorio commented May 24, 2019

Very helpful. Thanks :)

Loading

@hcbl1212
Copy link

hcbl1212 commented May 31, 2019

Nice!

Loading

@Kraloz
Copy link

Kraloz commented Jun 12, 2019

grande grande amigaRRRRRDO

Loading

@fgilio
Copy link
Author

fgilio commented Jun 12, 2019

Lol so now GitHub notifies me about comments on gists and I'm just now seeing all this comments.
I'm glad you found it useful

Loading

@fgilio
Copy link
Author

fgilio commented Jun 12, 2019

Just updated the code to also show how one would approach this using async/await and a simple try/catch

Loading

@aleixsuau
Copy link

aleixsuau commented Aug 6, 2019

👯

Loading

@sidneyyin
Copy link

sidneyyin commented Aug 7, 2019

In my app, I use Axios post to handle log in email and password functions, hashed, and then bcrypt to compare. When the password is entered incorrectly, Axios catches the error, and I console.log the error. However, it gives me everything in the config portion of the error response object, including the request itself, which includes the user email and password, unscrambled. Isn't this dangerous? How can I avoid this?

Loading

@fgilio
Copy link
Author

fgilio commented Aug 9, 2019

I don't know if that can be avoided, but I'm really interested in reading other people responses

Loading

@puffybsd
Copy link

puffybsd commented Aug 10, 2019

You could use destructuring to remove it, or use an authorization header or oidc flow instead.

Loading

@ronaldaraujo
Copy link

ronaldaraujo commented Aug 22, 2019

Thanks!

Loading

@gavinchua
Copy link

gavinchua commented Sep 6, 2019

Very useful!! Thanks!

Loading

@danger89
Copy link

danger89 commented Sep 15, 2019

Its good practice to return a Promose.reject! Example:

......() {
}
.then(response => {
   return response
})
.catch(error => {
   return Promise.reject(error.response)
})

Loading

@fgilio
Copy link
Author

fgilio commented Sep 15, 2019

Hey, thanks for the suggestion! Do you have any source to supplement that?

Loading

@danger89
Copy link

danger89 commented Sep 16, 2019

Yea.. but my code is closed (private market trading bot written in nodejs) sorry.

Optionally instead of using Promose.reject you could throw an error instead to stop the pipe line:

.catch(error => {
    throw new Error(error.reponse)
})

Loading

@fgilio
Copy link
Author

fgilio commented Sep 16, 2019

Honest question: What would be the advantage of using a catch if we're just going to throw the error again?

Loading

@danger89
Copy link

danger89 commented Sep 18, 2019

You convert a Promise catch to a Python try/catch, which are not the same (in this example).

You can also return a Promose.reject() as shown above, depending on what you want.

Loading

@danger89
Copy link

danger89 commented Sep 18, 2019

Loading

@fgilio
Copy link
Author

fgilio commented Sep 18, 2019

Ok ok, I think I now understand what you're saying.
But the thing is, you would only rethrow an exception if it's an unexpected one that you cannot handle in that catch block or if you want the exception to bubble up so you can catch it somewhere else. Am I right?

Loading

@alexalannunes
Copy link

alexalannunes commented Nov 26, 2019

Why I put console.log(error) the request property don't appears?

Loading

@fgilio
Copy link
Author

fgilio commented Nov 26, 2019

Hi @alexalannunes, can you share your code?

Loading

@stelco
Copy link

stelco commented Dec 9, 2019

Hi, I am using a service for the axios post request and getting error results back in the following format. What is the best way to send the ValidationResult back to my app?

CompanyName: "a"
ConfirmPassword: "Pass123!"
Email: ""
FirstName: "a"
OrisecAccountNumber: "a"
Password: "Pass123!"
Surname: "aa"
ValidationResult:
Errors: Array(1)
0:
Field: null
Message: "User name '
' is already taken."

Loading

@fgilio
Copy link
Author

fgilio commented Dec 14, 2019

Hi @stelco, I don't fully grasp your question... but 5 days later I imagine you already solved it. If so, may be a good idea to share your solution in a gist so others can benefit :)

Loading

@RELNO
Copy link

RELNO commented Dec 15, 2019

Loading

@fgilio
Copy link
Author

fgilio commented Dec 15, 2019

hey @fgilio, looks like fgilio/230ccd514e9381fafa51608fcf137253#file-axios-catch-error-js-L36 has an extra ';'

Indeed, thanks!

Loading

@prashant-rajoriya
Copy link

prashant-rajoriya commented Dec 17, 2019

How to catch 503 errors and it's code with the message received from the server?
Till now, I can only get the call-stack of the error. No useful information even if I jsonify the error.

Loading

@fgilio
Copy link
Author

fgilio commented Dec 17, 2019

Sounds like you've got a server side issue to solve

Loading

@prashant-rajoriya
Copy link

prashant-rajoriya commented Dec 17, 2019

Sounds like you've got a server-side issue to solve

yeah, It's like how I got a 503 "service not available", and other errors which are in "Network Error" into the JSON object of error. I wanted to differentiate between them. Like "Network Error" also corresponds to "Internet Connectivity also".

Loading

@Reez0
Copy link

Reez0 commented Feb 2, 2020

A couple of years late, but just wanted to leave a comment saying thanks. This was really helpful and informative. As a beginner I didn't even know the error was an object to begin with.

Loading

@fgilio
Copy link
Author

fgilio commented Feb 3, 2020

🤗glad it helped you

Loading

@dtourek
Copy link

dtourek commented Feb 23, 2020

thanks! This helped me a lot!

Loading

@fgilio
Copy link
Author

fgilio commented Feb 23, 2020

:D

Loading

@mokie-H
Copy link

mokie-H commented Feb 27, 2020

thanks bro!

Loading

@singleseeker
Copy link

singleseeker commented Feb 28, 2020

Great job , thank you.

Loading

@fgilio
Copy link
Author

fgilio commented Feb 28, 2020

I guess axios should add something like this to their docs 😅

Loading

@shimjudavid
Copy link

shimjudavid commented Apr 9, 2020

Thanks, @fgilio. Thanks a ton. Saved my hours.

Loading

@fgilio
Copy link
Author

fgilio commented Apr 10, 2020

🤗

Loading

@gelinger777
Copy link

gelinger777 commented Apr 27, 2020

thank you!

Loading

@iradupat
Copy link

iradupat commented May 14, 2020

thank you very much

Loading

@Somesa
Copy link

Somesa commented Jun 8, 2020

good guy

Loading

@AdelinaUwU
Copy link

AdelinaUwU 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

Loading

@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?

Loading

@AkshaySeth94
Copy link

AkshaySeth94 commented Jun 19, 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!

Loading

@jimmybatuhan
Copy link

jimmybatuhan commented Jun 20, 2020

Kudos to you sir!

Loading

@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);
        }

Loading

@chrisloughnane
Copy link

chrisloughnane commented Aug 27, 2020

cheers.

Loading

@afrontend
Copy link

afrontend commented Sep 18, 2020

Thank you!

Loading

@Avallos
Copy link

Avallos commented Nov 17, 2020

thanks man!

Loading

@hardik-jpm
Copy link

hardik-jpm commented Dec 30, 2020

Thanks a lot!

Loading

@eiberham
Copy link

eiberham commented Jan 14, 2021

Thank u !

Loading

@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!

Loading

@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

Loading

@valtermoore
Copy link

valtermoore commented Feb 12, 2021

Perfect !!

Loading

@rubensflinco
Copy link

rubensflinco commented Apr 28, 2021

:D

Loading

@fgilio
Copy link
Author

fgilio commented Apr 28, 2021

:D

Loading

@farhankassam2
Copy link

farhankassam2 commented Apr 29, 2021

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?

Loading

@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

Loading

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

Loading

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

Loading

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