Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 380
Tesmen Avatar asked May 24 '15 17:05

Tesmen


People also ask

How do I trigger a 404 error?

One typical trigger for an error 404 message is when the page has been deleted from the website. The page was moved to another URL and the redirection was done incorrectly. You entered an incorrect URL address. Although it happens very rarely, sometimes the server malfunctions.

What are two main causes of the 404 error message?

The typical trigger for an error 404 message is when website content has been removed or moved to another URL. There are also other reasons why an error message could appear. These include: The URL or its content (such as files or images) was either deleted or moved (without adjusting any internal links accordingly)

What is a 404 error log?

But when someone tries to access a page on your website which doesn't exist, your web server responds with an HTTP error code 404. This is an error that signifies an object has not been found. In the case of a missing post or page, a message relaying The 404 error will be displayed to visitors.

Why is error 404 so common?

You might see a 404 error because of a problem with the website, because the page was moved or deleted, or because you typed the URL wrong. 404 errors are less common today than they used to be, as websites now strive to automatically redirect visitors away from deleted pages.


1 Answers

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.

like image 157
Duco Avatar answered Sep 24 '22 04:09

Duco