591

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

axios
  .get('foo.example')
  .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'}

17 Answers 17

1086

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);
    }
  });
17
  • 29
    Can you explain the magic behind it automtatically turning into a string if I don't refer to the response property? Commented Aug 25, 2016 at 19:39
  • 27
    console.log uses the toString method to format Error objects. It has nothing to do with referring to the response property. Commented Aug 25, 2016 at 21:21
  • 9
    I'm still confused, is this spesific to error objects or? If I console.log an object, I get the object, not a string. Commented Aug 25, 2016 at 21:22
  • 9
    It depends on implementation. For example, node.js implementation of console.log handles Error objects as a special case. I cannot say how exactly it's implemented in browsers, but if you call console.log({ foo: 'bar' }); and console.log(new Error('foo')); in the Chrome DevTools Console, you will see that the results look different. Commented Aug 25, 2016 at 22:17
  • 11
    Must be a native thing then. It's still strange though. Commented Aug 25, 2016 at 22:40
79

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.example')
  .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.example')
  .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)
  })
3
  • 4
    I'm trying to get my team to switch over to Typescript for THIS kind of clarity.
    – GHOST-34
    Commented Dec 4, 2020 at 4:13
  • this makes everything easier because you can get all the properties of the type with intellisense, so you can know the proper structure of your response and error
    – Ger
    Commented Sep 13, 2021 at 14:33
  • I don't think the non-null assertion here (on the line if (reason.response!.status ...)) is safe—if you get a 0 status code (e.g. network died before a response was returned), reason.response will be undefined and you'll get a TypeError there.
    – Ian Kim
    Commented Jan 9, 2023 at 16:35
28

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))
  });
2
  • 1
    Currently, this does not work. It does not show the contents inside of error.response. Commented Jul 25, 2021 at 22:03
  • 3
    JSON.stringify(error) is a potential candidate for throwing Circular dependency error in this case.
    – Coke
    Commented Aug 13, 2021 at 15:06
23

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.example', {validateStatus: () => true})
14

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

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

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

0
12

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 });
});
2
  • 1
    What is the specific advantage when using interceptors?
    – spencer741
    Commented Mar 9, 2021 at 21:41
  • 1
    You can intercept requests or responses before they are handled by then or catch.
    – Tan
    Commented Mar 10, 2021 at 14:33
10

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

9

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

axios.get('url').catch((error) => {
      if (error.response) {
        console.log(error.response);
      }
    });
8
const handleSubmit = (e) => {
e.preventDefault();
// console.log(name);
setLoading(true);
createCategory({ name }, user.token)
  .then((res) => {
   // console.log("res",res);
    setLoading(false);
    setName("");
    toast.success(`"${res.data.name}" is created`);
    loadCategories();
  })
  .catch((err) => {
    console.log(err);
    setLoading(false);
    if (err.response.status === 400) toast.error(err.response.data);//explained in GD
  });

};

See the console log then you will understand clearly

enter image description here

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

      }
})
3
  • While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained.
    – Borja
    Commented Jan 14, 2021 at 7:11
  • I think I understand how this code works... its checking if response exist, then console.log... I think this is a good solution. Commented Mar 10, 2022 at 23:01
  • Please don't post code-only answers. Future readers will be grateful to see explained why this answers the question instead of having to infer it from the code. Also, since this is an old question, please explain how it complements the other answers. In fact, it's essentially identical to the accepted answer. Commented Jun 23, 2022 at 18:44
3

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

    })
2

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.

1

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.

1
  • 1
    This is not the same issue I'm having, there's not even an object involved when I log error Commented Aug 25, 2016 at 19:32
1

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

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

An Axios Error has a lot of information, but if you do a regular console.log(error) you would just get a 'string message' generic error like: "Error: Request failed with status code XXX"

A solution to handle Axios Error and other errors is:

axios.get('foo.example')
    .then((response) => {//...})
    .catch (error: any) {
        let errorResponse: any;

        // it is an AxiosError
        if (error?.isAxiosError) {
            const axiosError = error as AxiosError;
            errorResponse = axiosError.response; //all the info here
        } else {
            errorResponse = error; // it is not an AxiosError
        }

        console.log(errorResponse);
        throw errorResponse;
    }
0

I have a solution !

For me, problem was not in front, but in back application. It was "just" a CORS issue (but nothing was mentionning CORS anywhere). You need to allow CORS.

In my program.cs, I added this :

app.UseCors(options =>
{
    options.AllowAnyOrigin();
    options.AllowAnyHeader();
    options.AllowAnyMethod();
});

but, be carefull to add it before this :

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

(yes I know that I should not allow any cors but it is for tests, not production)

-1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.