Javascript 捕获 XHR 的 404 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30426277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:10:04  来源:igfitidea点击:

Catch a 404 error for XHR

javascriptjqueryajax

提问by Tesmen

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.

基本上,我必须创建一个 javascript APP 对象,它将对服务器的一系列异步请求进行排队,处理对 JSON 的响应,并从中记录错误。

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".

使用“try-catch”可以轻松捕获 JSON 处理错误,但浏览器控制台中仍会显示诸如 404、500 等服务器错误,而我需要将其静默记录到“APP.history”中。

I tried to implement it via the code below, but none of 404 errors fires one error. What am I doing wrong?

我试图通过下面的代码实现它,但 404 错误都不会触发一个错误。我究竟做错了什么?

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?

顺便说一句,如何使用 jQuery AJAX 来完成?

回答by Duco

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

404 状态不会触发 xhr.onerror() 因为,从技术上讲,这不是错误;404 本身就是一个有效的响应。

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.

一种解决方案是使用 loadend() 处理程序,它无论如何都会触发。然后检查 404 的状态,或您感兴趣的任何状态。

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.

XMLHttpRequestUpload 存在相同的方法。不幸的是,我们的浏览器供应商不允许我们在 2017 年以编程方式抑制网络错误。但是,可以使用控制台的过滤选项抑制网络错误。