fetch API or XMLHTTPRequest: How to get exact error reason for a network error?

Viewed 1489

How to retrieve exact information about a network error? Chrome browser prints things like "net::ERR_CONNECTION_TIMED_OUT" or "net::ERR_CERT_INVALID" into console but how can I retrieve them via JS? Is that possible to get them at all? Currently I use fetch API but I can switch to XMLHTTPRequest easily.

I need that to handle such errors to inform a user and let him know what does he need to do.

2 Answers

you can get the exact error as follow:

     fetch('url',
        {
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            method: "POST",
            body: JSON.stringify({data})
        })
        .then(function(response) {
            console.log(response);
            //handle here or in catch
         })
        .then(function(json){
            console.log("succeed json re");
        });

You'll get resolved response once your promise has been resolved.

Response.status will give you status code. Response.statusText will give you exact error description as ERR_CONNECTION_TIMED_OUT. which will be in case of errors and then response.ok will be false.

For more info: FETCH

Related