21

Basically, I had to create a javascript APP object, which will queue an sequence of asynchronous requests for the server, process response to JSON, and log errors from it.

JSON processing errors were caught easily with "try-catch", but server errors like 404, 500 etc. are still shown in the console of the browser, while I need to silently log it in "APP.history".

I tried to implement it via the code below, but none of 404 errors fires one error. 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 could it be done with jQuery AJAX?

MLavoie
  • 9,671
  • 41
  • 36
  • 56
Tesmen
  • 559
  • 1
  • 6
  • 21
  • You can check the `xhr.status` value. See http://stackoverflow.com/questions/10931270/capture-404-status-with-jquery-ajax – JanSc May 24 '15 at 17:30
  • have a look here > http://stackoverflow.com/questions/1442425/detect-xhr-error-is-really-due-to-browser-stop-or-click-to-new-page, I hope it answers your question – DKanavikar May 24 '15 at 17:38

1 Answers1

53

A 404 status will not trigger xhr.onerror() because, technically it's not an error; the 404 itself is a valid response.

One solution is to use the loadend() handler, which fires no matter what. Then check the status for 404, or whichever status you're 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 vendors don't allow us to programmatically suppress network errors in 2017. However, networks errors can be suppressed using the console's filtering options.

Duco
  • 721
  • 7
  • 11
  • 2
    @Tesmen should make this answer the correct one as 404 is not an error. It is a response code. Also, this answer worked for me. – DaveCat Mar 07 '19 at 16:54
  • @Duco Unfortunately, the error is reported at console level between event.target.readystate==1 and event.target.readystate==2; way before "loadend" comes into play. The output to console happens **between** readystate events; therefore, by the time readystate==2 informs us about the condition, a message (in red ink) has already been splattered onto the console. Is this what you meant by "our browser vendors dont allow us to programmatically suppress"? If so, thanks for providing an explanation for why I cant clean it up. – IAM_AL_X Apr 21 '20 at 16:44
  • That is what I meant IAM_AL_X. The user can stop the red ink using filter options in the dev tools, but the programmer has no control. – Duco Jan 14 '21 at 07:32