Catch 404 Error for XHR

In principle, I had a need to create a javascript APP object that would queue a sequence of asynchronous requests for the server, process the JSON response, and register errors from it.

JSON processing errors were easily fixed using try-catch, but server errors such as 404, 500, etc., still appear in the browser console, while I need to write it quietly in APP.history "

I tried to implement it using the code below, but none of the 404 errors worked. What am I doing wrong?

xhr = new XMLHttpRequest(); xhr.open("GET", url, true) xhr.onerror = function(){console.log("error")} xhr.upload.onerror = function(){console.log("error")} 

By the way, how can this be done using jQuery AJAX?

+6
source share
2 answers

Status 404 will not be xhr.onerror()

The solution is to use the loadend() handler, this works regardless of what you can check.

 xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.onloadend = function() { if(xhr.status == 404) throw new Error(url + ' replied 404'); } 
-2
source

I recently had to solve this problem myself. The 404 status does not trigger xhr.onerror (), because technically this is not an error, since the answer is complete (404 itself is the answer).

My solution was to use the loadend () handler, which fires no matter what then, then check the status for 404 or any status you are interested in.

 xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.onloadend = function() { if(xhr.status == 404) throw new Error(url + ' replied 404'); } 

The same method exists for XMLHttpRequestUpload. Unfortunately, our browser developers do not programmatically suppress network errors in 2017. However, network errors can be suppressed using console filtering options.

+21
source

Source: https://habr.com/ru/post/987827/


All Articles