axios: Set a code/status for "Network Error"

I’m trying to detect when my server is down so that I can display an appropriate error message to the user.

In this case, axios network requests throw an error which is different from all other axios errors, as discussed here: https://github.com/mzabriskie/axios/issues/204

In my code, it seems the only way to detect this error is to check err.message: if (err.message === "Network Error"){/*tell user the server is down*/}

This bothers me because string comparisons are a little risky; perhaps some day this message will be translated, and my code will fail.

It would be great if err.status or err.code (or err.???) were set to some documented value that we can check for in our code.

Is there any other way to detect this scenario that I’m missing? Thanks all!

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 72
  • Comments: 69 (2 by maintainers)

Most upvoted comments

It’s in error.response.status.

I’m having this issue. Can anyone help me please?

The server response is 401 but axios gives me this:

error --> “Network Error” error.response --> undefined error.status --> undefined

As someone said in #204, there are some cases where it is impossible to catch network errors in the browser, so Axios responds with a generic error (new Error('Network error')). If you want to distinguish them from bad responses (status code !== 2xx or custom check) I think the best way is just checking the status property instead of the error message. E.g.:

axios.request(options).catch(function(error) {
  if (!error.status) {
    // network error
  }
});

I think setting a custom status code would be a bad idea (it could cause more confusion) and setting a specific property would not help at all because we only have a single error case.

Of course in Node.js is easier because you have access to the actual error and can check according to the Node.js documentation.

This works, although I can’t seem to find documentation to support it. I am assuming that error.response should be empty on a network error otherwise it is an api error.

axios.request(options).catch(function(error) {
  if (!error.response) {
    // network error
  } else {
    // http status code
    const code = error.response.status
    // response data
    const response = error.response.data
  }
});

My problem was with Jest+ Axios. I solved it by adding this to my package.json:

"jest": {
    "testEnvironment": "node"
}

It might be a Cors Error.

When error is “network error” that means Axios coudn’t connect to your server, or for some reason does not get the response from your server. So that 401 error is never making it into Axios. Maybe post a question with some sample code on StackOverflow?

Ran into this when using AWS API-Gateway. For anyone seeing the same issues it’s a problem with 4xx errors (in my case a 401) not responding with the CORS headers. Spent hours troubleshooting this damn issue! Thanks @jonathan-stone for pointing my troubleshooting in the right direct.

So far, I cant able to get the error code like 404,500…, Still I am getting Network Error. How to solve this? instance.post(‘/foo’, {request_id : 12345}) .then(function(response) {}) .catch(function(error){ console.log(error); // Network Error console.log(error.status); // undefined console.log(error.code); // undefined });

As someone said in #204, there are some cases where it is impossible to catch network errors in the browser, so Axios responds with a generic error (new Error('Network error')). If you want to distinguish them from bad responses (status code !== 2xx or custom check) I think the best way is just checking the status property instead of the error message. E.g.:

axios.request(options).catch(function(error) {
  if (!error.status) {
    // network error
  }
});

I think setting a custom status code would be a bad idea (it could cause more confusion) and setting a specific property would not help at all because we only have a single error case.

Of course in Node.js is easier because you have access to the actual error and can check according to the Node.js documentation.

If you’re here from Google, note that this API is deprecated. This is from 2016, v <0.13.

You want to check for error.response when the server responds, error.response === undefined for offline status and the special case of error.code === 'ECONNABORTED' for timeouts.

Update: if anyone stumbles on this with API Gateway and CORS, you’ll need to add a response header to your responses:

access-control-allow-origin: *

Definitely don’t do this. Set the origins accordingly instead of *.

To solve the problem you need to specify always Nginx

add_header ‘Access-Control-Allow-Origin’ * always;

Sometimes it may be caused by the AD blockers in your browser … Try incognito or private mode, or download a new browser to test …

I can able to connect with my server, it actually returns 404 Error code and with some other API calls server returns 500 Internal server error, but still i can’t able to get the network error code through scripting(i.e.,console.log(error.status); // undefined ).

As @jonathan-stone said, I don’t think this can be rectified, because Axios simply doesn’t know what happened. It’s like sending your friend out for Funyuns and he says the store was closed. It says “always open” - why was the store closed. Did they close for good (404)? Is someone sick (500)? Did they run out of inventory (503)? He doesn’t know, they’re just closed (network error)!

I was getting this error when firing Axios in rapid succession against a local Express server trying to retrieve different kinds of data from my API. It’s not that Axios didn’t report a correct error - it can’t - my Express server didn’t respond with anything because it was too busy.

If I retry the request (using retry-axios from #164 ) I can get the data or maybe a real error if there’s something wrong with the AVAILABLE server.

I use this utility function to catch network errors from lower in the call stack (prevents identifying non-axios errors as network errors):

function isNetworkError(err) {
  return !!err.isAxiosError && !err.response;
}

See https://github.com/axios/axios/pull/1419

Same general problem here. For me it was definitely CORS. Browser was making OPTIONS requests to the server and I didn’t have a handler setup for them (in node). Axios would complete the (failed) request successfully but with an undefined response

      return axios.httpClients.server.post('/someUrl, {
        someData:some_data
      }).then(response => {
        console.log(response);
        //the following errors out because response is undefined
        if (response.data && response.data.success === true) {
        }
      }).catch(err => {
           //catch never triggered
            console.log(err)
      });

Does anyone have any solutions to this problem?

Network Error means Axios couldn’t connect to your server at all, so it can’t get any error code from the server. Maybe try it with another tool (curl, postman, or a browser) to ensure you can connect to it?

Hi guys, i have problem CORS error where was getting response with status 403 (4** & 5**) Nginx sending header “Access-Control-Allow-Origin” only for response status 2** & 3**.

i resolve this problem edit nginx config from: add_header 'Access-Control-Allow-Origin' '*'; to: add_header 'Access-Control-Allow-Origin' '*' always;

The Error still Exist , if any anybody has a solution for this issue Share with us please.

Just like this:

try {
  ...
  some code that calls axios
  ...
} catch (err) {
  if (isNetworkError(err)) return alert(‘check your connection);
  throw err;
}

I use this utility function to catch network errors from lower in the call stack (prevents identifying non-axios errors as network errors):

function isNetworkError(err) {
  return !!err.isAxiosError && !err.response;
}

See #1419

Solved the problem Thanks

Hi guys, we have set up entity size protection on our proxy, it returns generic error but I’m unable to get the 413 status code… is it somehow possible?

Screenshot 2019-05-07 at 14 19 26

To solve the problem you need to specify always Nginx

add_header ‘Access-Control-Allow-Origin’ * always;

Don’t do this. Never do this. You wouldn’t deactivate your firewall just to let one connection through.

Someone needs to buy @joelnet a beer. This saved my day:

https://github.com/axios/axios/issues/383#issuecomment-308606088

Other people might have different problems, but that worked for me.

Guys, I also struggling on this issue for quit while. But I figured out the issue of my axios post network createError on Android device now. The reason to axios Network Error is because the form data I passed to axios contains wrong type of data object I guess. I have include an image object(ImagePicker object from Expo) as a one of param of form data which not accept by axios I think. Axios might only receive string, float, int or image as param. image cannot pass as param, it is not an type of image, it is an react native object, I have removed it and include an image field as param by assign image.uri to value of param then it works. Hope this will help some of people who may encounter same problem as I was facing before. Deleting some of your form data one by one when you are testing axios Network error, you will find out which one is the cause of issue.

Not sure if this is applicable to other cases, but here is how I solved this same issue (considering that we are talking CORS).

On the Frontend side, make sure you are passing the headers as parameter in your PUT or POST requests:

const axiosParams = {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'application/json',
  },
};

axios.put(`${api.url}/like`, axiosParams)
  .then((response) => {
    // ...
  });

And on the Backend side, make sure that you are using CORS with Express:

// server.js
const express = require('express');
const app = express();

var cors = require('cors'); // Yep, you need to install this
app.use(cors()); // Works 🎉

Refs: here and here.

I’m having the same issue. I believe it’s an issue with CORS. Has anyone found a good solution for this?

I also got this error today, I don’t know what the problem is, this is my script:

   var url = "http://localhost:8000/";
   Axios.get(url).then(function(response){
     alert(response)
   }).catch(function(error){
     alert(error)
   });

http://localhost:8000/ returns a JSON response, this does not work on other hosts

@WarisR I have fixed this by allowing cors on the server-side. I thought Axios issue but actually it isn’t. I can help you if you let me know the issue that you’re really facing.

Add in the server 'Access-Control-Allow-Origin': '*'

When error is “network error” that means Axios coudn’t connect to your server, or for some reason does not get the response from your server. So that 401 error is never making it into Axios. Maybe post a question with some sample code on StackOverflow?

I’m also getting the same error, For me, It reaching the server and I’m responding with 403 and a JSON, which results in the Network Error in the Axios

I’m able to see the response in the browser network tab, but in the catch block err.response is undefined

image

image

I was having this error because I wasn’t specifying HTTP or https. Mainly code itself throw an error on protocol undefined. This should be handled or in error meta, it should be included.