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

98,417

Solution 1

Axios is probably parsing the response. I access the error like this in my code:

axios({
  method: 'post',
  responseType: 'json',
  url: `${SERVER_URL}/token`,
  data: {
    idToken,
    userEmail
  }
})
 .then(response => {
   dispatch(something(response));
 })
 .catch(error => {
   dispatch({ type: AUTH_FAILED });
   dispatch({ type: ERROR, payload: error.data.error.message });
 });

From the docs:

The response for a request contains the following information.

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the headers that the server responded with
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {}
}

So the catch(error => ) is actually just catch(response => )

EDIT:

I still dont understand why logging the error returns that stack message. I tried logging it like this. And then you can actually see that it is an object.

console.log('errorType', typeof error);
console.log('error', Object.assign({}, error));

EDIT2:

After some more looking around this is what you are trying to print. Which is a Javascipt error object. Axios then enhances this error with the config, code and reponse like this.

console.log('error', error);
console.log('errorType', typeof error);
console.log('error', Object.assign({}, error));
console.log('getOwnPropertyNames', Object.getOwnPropertyNames(error));
console.log('stackProperty', Object.getOwnPropertyDescriptor(error, 'stack'));
console.log('messageProperty', Object.getOwnPropertyDescriptor(error, 'message'));
console.log('stackEnumerable', error.propertyIsEnumerable('stack'));
console.log('messageEnumerable', error.propertyIsEnumerable('message'));

Solution 2

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

Solution 3

Here is the proper way to handle the error object:

axios.put(this.apiBaseEndpoint + '/' + id, input)
.then((response) => {
    // Success
})
.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 that triggered an Error
        console.log('Error', error.message);
    }
    console.log(error.config);
});

Origin url https://gist.github.com/fgilio/230ccd514e9381fafa51608fcf137253

Solution 4

axios.post('http://localhost:8000/api/auth/register', {
    username : 'test'
}).then(result => {
    console.log(result.data)
}).catch(err => {
    console.log(err.response.data)
})

add in catch geting error response ==> err.response.data

Solution 5

I was also stumped on this for a while. I won't rehash things too much, but I thought it would be helpful to others to add my 2 cents.

The error in the code above is of type Error. What happens is the toString method is called on the error object because you are trying to print something to the console. This is implicit, a result of writing to the console. If you look at the code of toString on the error object.

Error.prototype.toString = function() {
  'use strict';

  var obj = Object(this);
  if (obj !== this) {
    throw new TypeError();
  }

  var name = this.name;
  name = (name === undefined) ? 'Error' : String(name);

  var msg = this.message;
  msg = (msg === undefined) ? '' : String(msg);

  if (name === '') {
    return msg;
  }
  if (msg === '') {
    return name;
  }

  return name + ': ' + msg;
};

So you can see above it uses the internals to build up the string to output to the console.

There are great docs on this on mozilla.

Share:
98,417
Phillip Boateng
Author by

Phillip Boateng

Updated on November 24, 2021

Comments

  • Phillip Boateng
    Phillip Boateng over 2 years

    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.

  • Phillip Boateng
    Phillip Boateng almost 8 years
    Thanks for your detailed response, I went through the repository code which helped. Ultimately I logged the object and was able to see the response object and handle the data. additional code: let e = {...error} switch (e.response.data.type)
  • lucasmonteiro001
    lucasmonteiro001 about 7 years
    Exactly what i needed! Thx
  • Notorious
    Notorious almost 7 years
    Yes! Accessing err.response gets what I need, thanks!
  • tany4
    tany4 almost 2 years
    This helped me figure out my issue thanks!