catching error body using axios post

JavascriptPostAxios

Javascript Problem Overview


I am sending a status code 422 from my backend code with response body which contains the description of the error. I am using axios post as below to post a request:

post: function(url, reqBody) {
    const request = axios({
        baseURL: config.apiUrl,
        url: url,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': sessionStorage.getItem('token')
        },
        method: 'POST',
        data: reqBody,
        responseType: 'json'
    });
    return request
        .then((res) => {
            return res;
        })
        .catch((error) => {
            console.log(error);
            return error;
        })
}

The problem is when backend is returning error code 422, the error object I am catching has no information about response body. Is there any way I can retrieve the error text?

Javascript Solutions


Solution 1 - Javascript

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

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

For those using await/async and Typescript

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

Solution 4 - Javascript

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

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

Solution 6 - Javascript

I am returning a string from backend but expecting a json as response type. So I need to return an object instead of string for axios to process it properly.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmol AggarwalView Question on Stackoverflow
Solution 1 - JavascriptJoeTideeView Answer on Stackoverflow
Solution 2 - JavascriptZelig880View Answer on Stackoverflow
Solution 3 - JavascriptYayo ArellanoView Answer on Stackoverflow
Solution 4 - JavascriptRafael InácioView Answer on Stackoverflow
Solution 5 - JavascriptTopW3View Answer on Stackoverflow
Solution 6 - JavascriptAmol AggarwalView Answer on Stackoverflow