catching error body using axios post

Solution 1:

I had this same issue and the answer (as per Axios >= 0.13) is to specifically check error.response.data:

axios({
    ...
}).then((response) => {
    ....
}).catch((error) => {
    if( error.response ){
        console.log(error.response.data); // => the response payload 
    }
});

See here for more details.

Solution 2:

The "body" of an AXIOS error response depends from the type of response the request had.

If you would like full details about this issue you can see this blogpost: How to catch the body of an error in AXIOS.

In summary AXIOS will return 3 different body depending from the error:

  1. Wrong request, we have actually done something wrong in our request (missing argument, bad format), that is has not actually been sent. When this happen, we can access the information using error.message.

    axios.get('wrongSetup')
    .then((response) => {})
    .catch((error) => {
        console.log(error.message);
    })
    
  2. Bad Network request: This happen when the server we are trying to reach does not respond at all. This can either be due to the server being down, or the URL being wrong. In this case, we can access the information of the request using error.request.

    axios.get('network error')
    .then((response) => {})
    .catch((error) => {
        console.log(error.request );
    });
    
  3. Error status: This is the most common of the request. This can happen with any request that returns with a status that is different than 200. It can be unauthorised, not found, internal error and more. When this error happen, we are able to grasp the information of the request by accessing the parameter specified in the snippets below. For the data (as asked above) we need to access the error.response.data.

    axios.get('errorStatus')
    .then((response) => {})
    .catch((error) => { 
         console.log(error.response.data);  
         console.log(error.response.status);  
         console.log(error.response.headers); 
     })
    

Solution 3:

For those using await/async and Typescript

try {
    const response = await axios.post(url, body)
} catch (error) {
    console.log(error.response.data);
}

Solution 4:

For react native it just worked for me

api.METHOD('endPonit', body)
  .then(response => {
   //...
  })
  .catch (error => {
    const errorMessage = JSON.parse(error.request.response)
    console.log(errorMessage.message)
  })

Solution 5:

We can check error.response.data as @JoeTidee said. But in cases response payload is blob type? You can get error response body with the below code.

axios({
    ...
}).then((response) => {
    ....
}).catch(async (error) => {
    const response = error.response
    if(typeof response.data.text === function){
        console.log(await response.data.text()); // => the response payload 
    } else {
        console.log(response.data)
    }
});