How to catch and handle error response 422 with Redux/Axios?

Phillip Boateng picture Phillip Boateng · Aug 6, 2016 · Viewed 70.5k times · Source

I have an action making a POST request to the server in order to update a user's password, but I'm unable to handle the error in the chained catch block.

return axios({
  method: 'post',
  data: {
    password: currentPassword,
    new_password: newPassword
  },
  url: `path/to/endpoint`
})
.then(response => {
  dispatch(PasswordUpdateSuccess(response))
})
.catch(error => {
  console.log('ERROR', error)
  switch (error.type) {
    case 'password_invalid':
      dispatch(PasswordUpdateFailure('Incorrect current password'))
      break
    case 'invalid_attributes':
      dispatch(PasswordUpdateFailure('Fields must not be blank'))
      break
  }
})

When I log the error this is what I see:

Error Logged

When I check the network tab I can see the response body, but for some reason I can't access the values!

Network Tab

Have I unknowingly made a mistake somewhere? Because I'm handling other errors from different request fine, but can't seem to work this one out.

Answer

Steven Leggett picture Steven Leggett · Apr 5, 2017

Example

getUserList() {
    return axios.get('/users')
      .then(response => response.data)
      .catch(error => {
        if (error.response) {
          console.log(error.response);
        }
      });
  }

Check the error object for response, it will include the object you're looking for so you can do error.response.status

enter image description here

https://github.com/mzabriskie/axios#handling-errors