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

This comment has been minimized.

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?

@Peace-N

This comment has been minimized.

Copy link

Peace-N commented Dec 14, 2017

Perfect was looking for this Gist !!!

@jplew

This comment has been minimized.

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

@rodhoward

This comment has been minimized.

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.

@rdemorais

This comment has been minimized.

Copy link

rdemorais commented Apr 15, 2018

Thanks, man

@stefmabo

This comment has been minimized.

Copy link

stefmabo commented Jun 24, 2018

Thanks :)

@behouba

This comment has been minimized.

Copy link

behouba commented Jul 12, 2018

great !!! thanks very helpful

@sooraj007ks

This comment has been minimized.

Copy link

sooraj007ks commented Jul 16, 2018

Thanks

@NotIntMan

This comment has been minimized.

Copy link

NotIntMan commented Aug 27, 2018

Awesome:) It was useful:)

@rerodrigues

This comment has been minimized.

Copy link

rerodrigues commented Sep 12, 2018

Really useful! Thanks!

@felipe-machado

This comment has been minimized.

Copy link

felipe-machado commented Oct 9, 2018

Just what I needed. Thanks!

@chriswaweru70

This comment has been minimized.

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>`

@chriswaweru70

This comment has been minimized.

Copy link

chriswaweru70 commented Oct 14, 2018

#having trouble with thisc code too

@abh153k

This comment has been minimized.

Copy link

abh153k commented Mar 10, 2019

This is very helpful. THanks!

@clitorio

This comment has been minimized.

Copy link

clitorio commented May 24, 2019

Very helpful. Thanks :)

@hcbl1212

This comment has been minimized.

Copy link

hcbl1212 commented May 31, 2019

Nice!

@Kraloz

This comment has been minimized.

Copy link

Kraloz commented Jun 12, 2019

grande grande amigaRRRRRDO

@fgilio

This comment has been minimized.

Copy link
Owner 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

@fgilio

This comment has been minimized.

Copy link
Owner 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

@aleixsuau

This comment has been minimized.

Copy link

aleixsuau commented Aug 6, 2019

👯

@sidneyyin

This comment has been minimized.

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?

@fgilio

This comment has been minimized.

Copy link
Owner 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

@puffybsd

This comment has been minimized.

Copy link

puffybsd commented Aug 10, 2019

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

@ronaldaraujo

This comment has been minimized.

Copy link

ronaldaraujo commented Aug 22, 2019

Thanks!

@gavinchua

This comment has been minimized.

Copy link

gavinchua commented Sep 6, 2019

Very useful!! Thanks!

@danger89

This comment has been minimized.

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

This comment has been minimized.

Copy link
Owner Author

fgilio commented Sep 15, 2019

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

@danger89

This comment has been minimized.

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

This comment has been minimized.

Copy link
Owner 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?

@danger89

This comment has been minimized.

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.

@danger89

This comment has been minimized.

@fgilio

This comment has been minimized.

Copy link
Owner 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?

@alexalannunes

This comment has been minimized.

Copy link

alexalannunes commented Nov 26, 2019

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

@fgilio

This comment has been minimized.

Copy link
Owner Author

fgilio commented Nov 26, 2019

Hi @alexalannunes, can you share your code?

@stelco

This comment has been minimized.

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

@fgilio

This comment has been minimized.

Copy link
Owner 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 :)

@RELNO

This comment has been minimized.

@fgilio

This comment has been minimized.

Copy link
Owner Author

fgilio commented Dec 15, 2019

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

Indeed, thanks!

@prashant-rajoriya

This comment has been minimized.

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.

@fgilio

This comment has been minimized.

Copy link
Owner Author

fgilio commented Dec 17, 2019

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

@prashant-rajoriya

This comment has been minimized.

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

@Reez0

This comment has been minimized.

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.

@fgilio

This comment has been minimized.

Copy link
Owner Author

fgilio commented Feb 3, 2020

🤗glad it helped you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.