Amol Aggarwal
Amol Aggarwal

Reputation: 2824

catching error body using axios post

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?

Upvotes: 124

Views: 151108

Answers (8)

Davide Bruner
Davide Bruner

Reputation: 1

I faced the same issue recently. Using Axios interceptors for handling responses helped me get the error details:

// Create an Axios instance
const fetcher = axios.create({
    baseURL: config.apiUrl,
    headers: {
        'Content-Type': 'application/json',
        'Authorization': sessionStorage.getItem('token')
    }
});

// Response interceptor
fetcher.interceptors.response.use(
    (response) => {
        return response;
    },
    (error) => {
        console.error("response error:", error.response.data);
        return Promise.reject(error.response.data);
    }
);

// Using the fetcher instance for a post request
fetcher.post('/your-endpoint', reqBody)
    .then((res) => {
        console.log("Success:", res);
    })
    .catch((error) => {
        console.error("Error:", error);
    });

Upvotes: 0

Jakub Słowikowski
Jakub Słowikowski

Reputation: 1573

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

Upvotes: 2

Zelig880
Zelig880

Reputation: 638

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

Upvotes: 44

TopW3
TopW3

Reputation: 1527

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

Upvotes: 3

Rafael Inácio
Rafael Inácio

Reputation: 191

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

Upvotes: 9

Yayo Arellano
Yayo Arellano

Reputation: 3866

For those using await/async and Typescript

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

Upvotes: 29

JoeTidee
JoeTidee

Reputation: 26124

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.

Upvotes: 215

Amol Aggarwal
Amol Aggarwal

Reputation: 2824

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.

Upvotes: 0

Related Questions