111

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?

Talha Awan
  • 4,573
  • 4
  • 25
  • 40
Amol Aggarwal
  • 2,674
  • 3
  • 24
  • 32

7 Answers7

202

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.

JoeTidee
  • 24,754
  • 25
  • 104
  • 149
41

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); 
     })
    
Zelig880
  • 500
  • 4
  • 6
  • 2
    `This can happen with any request that returns with a status that is different than 200.` I would say other than 2XX/3XX. – Andrii Abramov Dec 05 '21 at 23:27
  • 1
    Nice overview. But maybe worth mentioning that the server might answer, but the `error.response` might be `undefined` anyway. Happens to me if our server sends 504 (including some HTML data). I guess this is because the browser blocks due to CORS ? – kca Dec 08 '21 at 12:41
26

For those using await/async and Typescript

try {
    const response = await axios.post(url, body)
} catch (error) {
    console.log(error.response.data);
}
Yayo Arellano
  • 3,575
  • 23
  • 28
9

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)
  })
Rafael Inácio
  • 161
  • 1
  • 4
2

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)
    }
});
TopW3
  • 1,477
  • 1
  • 8
  • 14
1

In my case I wanted to retrieve a response 404 error message (body). I got body with error.response.data but I couldn't display it because the type was ArrayBuffer.

Solution:

axios.get(url, { responseType: 'arraybuffer' }).then(
   response => {...},
   error => {
      const decoder = new TextDecoder()
      console.log(decoder.decode(error.response.data))
   }
)

Related posts: Converting between strings and ArrayBuffers

Jakub Słowikowski
  • 1,063
  • 1
  • 8
  • 13
0

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.

Amol Aggarwal
  • 2,674
  • 3
  • 24
  • 32