DEV Community

Mr_SC
Mr_SC

Posted on • Originally published at zelig880.com

How to catch the body of an AXIOS error

If you have been searching the web for some information about AXIOS error messages, and would like to understand how to use them, then you have come to the right place.

TLTR; Find the code snippets in the following section

If you search the web on this topic, all you can find is:

The list could have gone on and on, but they all ask for the sample simple question:

How can someone get the actual error information coming from a bad request made with AXIOS.

In this post we are going to provide information on “why” so many people ask for information, and “how” this information can be found.

Why so many people ask for this

If you have ever worked with an api, you perfectly know that request not always go to plan. You hope to always get a lovely response with a status of 200, but this does not always happens.

In many instances the status of our request may return some kind of error (400, 500), and when this happens we would like to be able to have a readable error message.

axios.get('EndpointWithAuthorizedError')
    .then((response) => {})
    .catch((error) => {
        console.log(error);
    })
Enter fullscreen mode Exit fullscreen mode

Unfortunately if the above would ever fail with a meaningful error, we would still see this within our console, as the variable passed by the catch statement seem to be of type “string”.

Error: Request failed with status code 401
Enter fullscreen mode Exit fullscreen mode

This is actually the main reason why so many people are “forced” to ask for help.

How can we process AXIOS error message

There is actually no magic when processing the error messages. In fact, the catch is in the fact that the variable received by the catch statement seem to be a string, but in reality it is not.

The AXIOS error message can actually return 3 different structure, depending from what kind of failure it has (crazy right… I thought that too).

Error in setting up the request

This error can happen if we have made an actual mistake in setting up the AXIOS request. It could be something with the data passed, or a configuration setting.

When this happen we can actually find the information we need by accessing the message parameter of the catch.

axios.get('wrongSetup')
    .then((response) => {})
    .catch((error) => {
        console.log(error.message);
    })

//or using destructuring
axios.get('wrongSetup')
    .then((response) => {})
    .catch(({message) => {
        console.log(message);
    })
Enter fullscreen mode Exit fullscreen mode

No response – Network Error

This scenario will take place when our request had no response at all. This can happen when the URL is incorrect, or if the receiving server is down.

When this happen we can access more information about our request bu accessing the request parameter. This will return the actual “request” information.

axios.get('network error')
     .then((response) => {})
     .catch((error) => {
         console.log(error. request );
     })
//or using destructuring
 axios.get('network error')
     .then((response) => {})
     .catch(({ request ) => {
         console.log( request );
     })
Enter fullscreen mode Exit fullscreen mode

Request returned with an error status

This is one of the most common, or more specifically the one type of “error” that need to be manage to make sure our web applications function properly.

There are hundreds of status code differently than 200 (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status), that would fit in this category. I am going to list below the most important:

  • 400: Bad request
  • 401: Unauthorized
  • 403: Forbidden
  • 404: Not Found
  • 500: Internal Server error
  • 502: Bad Gateway

When any of the above happen, we would like to know more about the request. In this case there are more information provided to us: data, status, header.

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

//or using destructuring
 axios.get('errorStatus')
     .then((response) => {})
     .catch(({ response }) => { 
         console.log(response.data);  
         console.log(response.status);  
         console.log(response.headers);  
     })
Enter fullscreen mode Exit fullscreen mode

With the above code, we will be able to get all the information we need about the response to our request. These includes the status code, the header and last but not least the data that the server has sent with the request.

When using any kind of API, the data parameter is going to include essential information, usually used for development purposes, but at times also good to show to the end users.

I hope to have saved you some time, and please feel free to comment, or provide suggestion to improve this post and help future readers

Top comments (8)

Collapse
 
andersonengenheiro profile image
Anderson S Souza

Good Job.

Collapse
 
flamingo_del_khesous profile image
Triquetra • Edited

this doesn't help me, I have api that returns 400 as bad request, with a body, I can't read the body from response since the request is directly thrown to catch where there's no body!
Any suggestions please?

*Actually I found the solution: *

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

Enter fullscreen mode Exit fullscreen mode
Collapse
 
mohdahmad1 profile image
Mohd Ahmad • Edited

try

JS

 try {
  // with destructuring 
  const res = await axios.get('https://example.com/someApi');

  // without destructuring 
   const res = await axios.get('https://example.com/someApi');

    return res.data;
  } catch (err) {
    console.log(`Error: ${err?.response?.data}`);
  }
Enter fullscreen mode Exit fullscreen mode

For TypeScript

 try {
  // with destructuring 
  const res = await axios.get<{ feild: type} >('https://example.com/someApi');

  // without destructuring 
   const res = await axios.get<{ feild: type} >('https://example.com/someApi');

    return res.data;
  } catch (err) {
    console.log(`Error: ${(err as AxiosError)?.response?.data}`);
  }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
anttibull profile image
anttibull

Thank you!

Collapse
 
catheryn profile image
Esther • Edited

This didnt work for me:
code:

return axios.put('/upload', data, config)
    .then(response => {
        return response.data.result
    })
    .catch((err) => {
        console.log(err)
        throw new Error(err)
    })
Enter fullscreen mode Exit fullscreen mode

result:
Error: AxiosError: Request failed with status code 400
at onResponseError

Collapse
 
catheryn profile image
Esther

Update:

I was unable to get this because in my intercepted I was using throw new Error instead of return Promise.reject(err)

Collapse
 
sccofield profile image
Michael Umanah

This is a life saver.

Collapse
 
mirocosic profile image
Miro

Nice! Check your destructuring code examples, there are some typos.
Other than that, great article!
Cheers!