Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set a code/status for "Network Error" #383

Closed
jonathan-stone opened this issue Jul 19, 2016 · 69 comments
Closed

Set a code/status for "Network Error" #383

jonathan-stone opened this issue Jul 19, 2016 · 69 comments

Comments

@jonathan-stone
Copy link

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: #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!

@mzabriskie
Copy link
Member

I think you're right. A status code would make sense.

@rubennorte
Copy link
Member

rubennorte commented Jul 20, 2016

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.

@jonathan-stone
Copy link
Author

Ah, so any error thrown by an Axios call is guaranteed to either 1) have a status, or 2) be a generic network error? I suppose that's good enough.

@ShivakumarRavi
Copy link

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

@jonathan-stone
Copy link
Author

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?

@ShivakumarRavi
Copy link

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

@jonathan-stone
Copy link
Author

It's in error.response.status.

@fgiarritiello
Copy link

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

@jonathan-stone
Copy link
Author

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?

@codygreen
Copy link

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.

@fgiarritiello
Copy link

@codygreen I'm still having this issues and I ran into this https://forums.aws.amazon.com/message.jspa?messageID=763752

Have you found a workaround?

@diegorodriguesvieira
Copy link

Does anyone have any solutions to this problem?

@joelnet
Copy link

joelnet commented Jun 15, 2017

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

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

@hammadzz
Copy link

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

@rexgama
Copy link

rexgama commented Jul 20, 2017

Did anyone find a best solution about this? Axios people make some noise :(

@samayo
Copy link

samayo commented Aug 9, 2017

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

@irfanevrens
Copy link

It might be a Cors Error.

@dcshiman
Copy link

Line 87, it has been set to 'Network Error' in the xhr adapter ? how to change this so that the error can be caught ?

request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(createError('Network Error', config, null, request));
// Clean up request
request = null;
};

@dcshiman
Copy link

My bad, its not an issue but expected behavior due to browser security. XHR error responses now receives an ProgressEvent on error status codes.

@amir-beheshty
Copy link

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

@hammadzz
Copy link

hammadzz commented Feb 8, 2018

@codygreen did you manage to fix your issue with API Gateway? Can't even figure out the response status code to help me debug further.

@juanp123
Copy link

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

@dcshiman
Copy link

dcshiman commented Feb 20, 2018

What is your response code of the response? if it's a network error, when using the Fetch API browsers will log it to the console but not pass it to JavaScript for security reasons hence the body is empty. See FETCH STANDERS, if you want to access the network errors of the response, change the HTTP response code to 200 and include the error message in the body of the response.

@hammadzz
Copy link

My problem was a dns issue. It worked in postman but failed in axios. Tried a curl to find out that it was also failing there. So my DNS was not configured correctly. Check that if you run into this issue.

@ComputerCarl
Copy link

I don't know if this helps you, but I had created an application which was proxying requests. The framework I was using was gobbling up the Express error. Finally, after explicitly forwarding the error res.send({ message: messageFromProxy });, I was able to see an error and deal with it on the client.

Good luck.

@balwant-sd
Copy link

balwant-sd commented Jun 3, 2019

@jonathan-stone said, Network Error means Axios couldn't connect to your server at all, so it can't get any error code from the server.

may be this will help someone.

error.data ;

@ketysek
Copy link

ketysek commented Jun 3, 2019

@balwant-sd as you can see on the screenshot I've sent here, the browser correctly recognises the 413 status code, but axios doesn't

Even in network tab I can see 413 status code...
Screenshot 2019-06-03 at 15 42 12

@dkagle
Copy link

dkagle commented Jun 14, 2019

As mentioned above a Login POST that returns a 401 error returns just 'Network Error' with code as undefined instead of 401.

@Falkyouall
Copy link

So this error seems to be a misconfigured CORS error which reflects just on your network tab. I have the same issue as @ketysek, and it seems that my ngnix is not applying CORS for this. As before mentioned, a generic network error will never make it into axios error.response. Here i like to blame the Backend.. oh wait, i did that...

@amitjoshi2188
Copy link

Hello i am also having same issue, even request getting proper response axios always return "Network Error" and goes to .catch(function(error) {}); par. is any one having solution for this problem ?

@koladev32
Copy link

I had the same problem today. This issue is mostly about the backend not allowing origins cross site HTTP requests. In my case, I am using django so I just placed the corsheaders class as high as possible to the MIDDLEWARE :
MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', //..etc ]
And I created a CORS_ORIGIN_WHITELIST to only allow certain origins :
CORS_ORIGIN_WHITELIST = [ "http://localhost:8081" , //..etc ]
This is for django-cors-headers. If you are not a django user, you should check the documentation of your favorite cors headers module.

@ErAz7
Copy link

ErAz7 commented Oct 7, 2019

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.

the problem with this approach is let's say we run some code in axios.then and the code has some error, for example "assignment to constant" (which was my case), with the approach you mentioned, we will get network error for "assignment to constant"

code example :

axios(options).then(() => {
  const foo = '';
  foo = 'bar'; // will throw error "assignment to constant"
}).catch(error => {
  if (!error.status) {
    // "assignment to constant" will be considered as network error
  }
})

@mifi
Copy link

mifi commented Oct 8, 2019

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

@ErAz7
Copy link

ErAz7 commented Oct 8, 2019

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

@hwhelchel
Copy link

@mifi can you show a more detailed example of how you're using isNetworkError to prevent identifying non-axios errors as network errors?

@mifi
Copy link

mifi commented Oct 20, 2019

Just like this:

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

@webjay
Copy link

webjay commented Oct 22, 2019

If it's a CORS error and you use Serverless, this can fix it:

resources:
  Resources:
    # CORS for 4xx errors
    GatewayResponseDefault4XX:
      Type: 'AWS::ApiGateway::GatewayResponse'
      Properties:
        ResponseParameters:
          gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
          gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
        ResponseType: DEFAULT_4XX
        RestApiId:
          Ref: 'ApiGatewayRestApi'

@estellederrien
Copy link

@narenderv7
Copy link

narenderv7 commented Nov 15, 2019

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

@WarisR
Copy link

WarisR commented Dec 3, 2019

@narenderv7 me too

@narenderv7
Copy link

narenderv7 commented Dec 3, 2019

@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': '*'

@abdelaziz321
Copy link

@ketysek I'm having the same error

Screenshot from 2019-12-26 16-48-22

did you find a way to catch this error?

@Popov-VV
Copy link

Popov-VV commented Dec 29, 2019

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;

@hnrqsss
Copy link

hnrqsss commented Jan 10, 2020

I have the same issue i'm test it using axios 0.18.0 and 0.19.0

Steps:
i made i request with expired token sometimes the error.response came correctly, but sometimes the error response came undefined and the message is 'Network error'. Why is this happens thats a backend error or a bug in axios?

@kenberkeley
Copy link

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

@WarisR
Copy link

WarisR commented Jan 21, 2020

@narenderv7 Yes, it's server side mistake. But I think Axios should be able to handle an error of this case, right?

@luatnd
Copy link

luatnd commented Jan 22, 2020

I need to distingue those two cases:

As I checked. error return by the catch block is the same in both cases above.

There still an issue:
#1296

@Ouael-Ben
Copy link

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

@angus96
Copy link

angus96 commented Apr 15, 2020

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

the timeout error can also match those conditions.
image

@axios axios locked and limited conversation to collaborators May 21, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests