Catch a 404 error for XHR

前端 未结 1 703
傲寒
傲寒 2021-01-07 19:16

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

相关标签:
1条回答
  • 2021-01-07 19:42

    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.

    0 讨论(0)
提交回复
热议问题