How can I get the status code from an HTTP error in Axios?

JavascriptAxios

Javascript Problem Overview


This may seem stupid, but I'm trying to get the error data when a request fails in Axios.

axios
  .get('foo.com')
  .then((response) => {})
  .catch((error) => {
    console.log(error); //Logs a string: Error: Request failed with status code 404
  });

Instead of the string, is it possible to get an object with perhaps the status code and content? For example:

Object = {status: 404, reason: 'Not found', body: '404 Not found'}

Javascript Solutions


Solution 1 - Javascript

What you see is the string returned by the toString method of the error object. (error is not a string.)

If a response has been received from the server, the error object will contain the response property:

axios.get('/foo')
  .catch(function (error) {
    if (error.response) {
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    }
  });

Solution 2 - Javascript

With TypeScript, it is easy to find what you want with the right type.

This makes everything easier because you can get all the properties of the type with autocomplete, so you can know the proper structure of your response and error.

import { AxiosResponse, AxiosError } from 'axios'

axios.get('foo.com')
  .then((response: AxiosResponse) => {
    // Handle response
  })
  .catch((reason: AxiosError) => {
    if (reason.response!.status === 400) {
      // Handle 400
    } else {
      // Handle else
    }
    console.log(reason.message)
  })

Also, you can pass a parameter to both types to tell what are you expecting inside response.data like so:

import { AxiosResponse, AxiosError } from 'axios'
axios.get('foo.com')
  .then((response: AxiosResponse<{user:{name:string}}>) => {
    // Handle response
  })
  .catch((reason: AxiosError<{additionalInfo:string}>) => {
    if (reason.response!.status === 400) {
      // Handle 400
    } else {
      // Handle else
    }
    console.log(reason.message)
  })

Solution 3 - Javascript

As @Nick said, the results you see when you console.log a JavaScript Error object depend on the exact implementation of console.log, which varies and (imo) makes checking errors incredibly annoying.

If you'd like to see the full Error object and all the information it carries bypassing the toString() method, you could just use JSON.stringify:

axios.get('/foo')
  .catch(function (error) {
    console.log(JSON.stringify(error))
  });

Solution 4 - Javascript

There is a new option called validateStatus in request config. You can use it to specify to not throw exceptions if status < 100 or status > 300 (default behavior). Example:

const {status} = axios.get('foo.com', {validateStatus: () => true})

Solution 5 - Javascript

You can use the spread operator (...) to force it into a new object like this:

axios.get('foo.com')
    .then((response) => {})
    .catch((error) => {
        console.log({...error}) 
})

Be aware: this will not be an instance of Error.

Solution 6 - Javascript

I am using this interceptors to get the error response.

const HttpClient = axios.create({
  baseURL: env.baseUrl,
});

HttpClient.interceptors.response.use((response) => {
  return response;
}, (error) => {
  return Promise.resolve({ error });
});

Solution 7 - Javascript

In order to get the http status code returned from the server, you can add validateStatus: status => true to axios options:

axios({
    method: 'POST',
    url: 'http://localhost:3001/users/login',
    data: { username, password },
    validateStatus: () => true
}).then(res => {
    console.log(res.status);
});

This way, every http response resolves the promise returned from axios.

https://github.com/axios/axios#handling-errors

Solution 8 - Javascript

Whole error can only be shown using error.response like that :

axios.get('url').catch((error) => {
      if (error.response) {
        console.log(error.response);
      }
    });

Solution 9 - Javascript

With Axios

    post('/stores', body).then((res) => {

        notifyInfo("Store Created Successfully")
        GetStore()
    }).catch(function (error) {

        if (error.status === 409) {
            notifyError("Duplicate Location ID, Please Add another one")
        } else {
            notifyError(error.data.detail)
        }

    })

Solution 10 - Javascript

You can put the error into an object and log the object, like this:

axios.get('foo.com')
    .then((response) => {})
    .catch((error) => {
        console.log({error}) // this will log an empty object with an error property
    });

Hope this help someone out there.

Solution 11 - Javascript

It's indeed pretty weird that fetching only error does not return an object. While returning error.response gives you access to most feedback stuff you need.

I ended up using this:

axios.get(...).catch( error => { return Promise.reject(error.response.data.error); });

Which gives strictly the stuff I need: status code (404) and the text-message of the error.

Solution 12 - Javascript

This is a known bug, try to use "axios": "0.13.1"

https://github.com/mzabriskie/axios/issues/378

I had the same problem so I ended up using "axios": "0.12.0". It works fine for me.

Solution 13 - Javascript

It's my code: Work for me

 var jsonData = request.body;
    var jsonParsed = JSON.parse(JSON.stringify(jsonData));

    // message_body = {
    //   "phone": "5511995001920",
    //   "body": "WhatsApp API on chat-api.com works good"
    // }

    axios.post(whatsapp_url, jsonParsed,validateStatus = true)
    .then((res) => {
      // console.log(`statusCode: ${res.statusCode}`)

            console.log(res.data)
        console.log(res.status);

        // var jsonData = res.body;
        // var jsonParsed = JSON.parse(JSON.stringify(jsonData));

        response.json("ok")
    })
    .catch((error) => {
      console.error(error)
        response.json("error")
    })

Solution 14 - Javascript

Axios. get('foo.com')
.then((response) => {})
.catch((error) => {
    if(error. response){
       console.log(error. response. data)
       console.log(error. response. status);

      }
})

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
QuestionSebastian OlsenView Question on Stackoverflow
Solution 1 - JavascriptNick UraltsevView Answer on Stackoverflow
Solution 2 - JavascriptYan QiDongView Answer on Stackoverflow
Solution 3 - JavascriptdaniiView Answer on Stackoverflow
Solution 4 - JavascriptDmytro NaumenkoView Answer on Stackoverflow
Solution 5 - JavascriptMoses SchwartzView Answer on Stackoverflow
Solution 6 - JavascriptTanView Answer on Stackoverflow
Solution 7 - JavascriptEmre TapcıView Answer on Stackoverflow
Solution 8 - JavascriptManik VermaView Answer on Stackoverflow
Solution 9 - JavascriptRumesh MadushankaView Answer on Stackoverflow
Solution 10 - JavascriptMendyView Answer on Stackoverflow
Solution 11 - JavascriptBogdan AntoneView Answer on Stackoverflow
Solution 12 - JavascriptDmitriy NevzorovView Answer on Stackoverflow
Solution 13 - JavascriptRodrigo GrossiView Answer on Stackoverflow
Solution 14 - JavascriptVigneshView Answer on Stackoverflow