Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle JavaScript Fetch errors?

Tags:

If a fetch call fails in Chrome, then the only error details that I get back is

TypeError: Failed to fetch

How do I display an informative error message to the end user in this case?

Specifically:

Is it possible to get any details about why fetch failed?

For example, if the server crashed, Chrome DevTools might log a console message of net:ERR_EMPTY_RESPONSE, but there appears to be no way to access this from JavaScript.

As far as I can tell, the answer is no; I assume this is for security reasons, to avoid letting malicious JS find out which sites are and aren't accessible by inspecting error messages.

Is it possible to distinguish fetch errors from other TypeErrors?

If I can't get error details, I'd like to at least replace the horribly vague "Failed to fetch" with an informative "Failed to access the web site; please try again later" message, and I'd like to do this without any risk of displaying that message for other TypeErrors.

The only solution I've found here is to check the actual message to see if it's "Failed to fetch". This is obviously browser-specific; it works in Chrome, it seems like it will work in any user language of Chrome, and other browsers would need their own testing and handling.

like image 510
Josh Kelley Avatar asked Sep 08 '16 14:09

Josh Kelley


People also ask

How do you handle failed to fetch error?

If you're making a POST , PUT or PATCH request, make sure the body is passed to the JSON. stringify() method in the call to fetch . If the configuration you pass to the fetch method is correct, check if your server is sending the correct CORS headers in the response.

How do you handle JavaScript errors?

JavaScript provides error-handling mechanism to catch runtime errors using try-catch-finally block, similar to other languages like Java or C#. try: wrap suspicious code that may throw an error in try block. catch: write code to do something in catch block when an error occurs.


1 Answers

It seems likely that there aren't any more details for networking/permission/input problems.

Is it possible to distinguish fetch errors from other TypeErrors?

Yes, you just need to catch only the the errors from the fetch call:

fetch(…) .catch(err => new FetchError(err)) .…  class FetchError extends Error {     constructor(orig) {         super();         this.message = "fetch error";         this.details = orig;     } } 
like image 129
Bergi Avatar answered Oct 14 '22 01:10

Bergi