Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

javascript - Catch a 404 error for XHR

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...