console log an error when fetching a 404 response [duplicate] - javascript

I'm writing a script that uses an XMLHttpRequest to search for a file defined by a relative path, by attempting to resolve that relative path against other same domain absolute paths that the script is aware of, then attempting to load the file from that resolved url. If I encounter a 404, I just try to resolve the files relative path against another absolute path, and try again. For this particular script, its perfectly fine to encounter a 404- however, my console is littered with 'Failed to load resource: the server responded with a status of 404 (Not Found) messages, and I want to suppress them.
There is no error to catch as far as I can see- error cases are handled by the xmlHttpRequest.onreadystatechange handler, and there is no window.onerror.
Is there any way to suppress these messages?
Thanks

This feature was introduced last year. You can enable it here: DevTools->Settings->General->Console->Hide network messages.
See also Filtering the Console output and Additional settings in the devtools documentation.

Use console.clear() in the catch block or error handler function.
It will clear those request error on the console immediately after it is logged.
PLEASE NOTE
From MDN
Note that in Google Chrome, console.clear() has no effect if the user has selected "Preserve log upon navigation" in the settings.
Read more about it on MDN
try {
var req = new XMLHttpRequest();
req.open('GET', 'https://invalidurl', false);
req.send();
} catch(e) {
console.clear();
}
Should log this
GET https://invalidurl/ net::ERR_NAME_NOT_RESOLVED
but it will be cleared.

If you use a web worker to perform XMLHttpRequest requests, the errors will be logged into the worker script context so they will not appear on the console unless this context will be specifically chosen for display.

Related

What's causing this error when running a web worker?

First time using web workers and I get this error when I try to run it.
First I get a very generic error event sent to my worker.onerror handler. It does not have the message property, the only information is the property type which says error.
Looking at the network tab in dev tools, the request for the worker script looks like it succeeds but it only has provisional response headers and no content to preview.
Preview has:
failed to load response data: connection is closed, can't dispatch pending call to Network.getResponseBody
This caused me to waste about an hour searching for web worker errors. Anyway it turns out that you can get this error if you have a syntax error in your Javascript. At least that is what got me.

Fetch returning 404 error: "GET <urlthatIwasfetchinghere> 404 (Not Found)"

I am using fetch and it is to my understanding that 404 codes should happen but not GET 404 errors when fetching from a non existent page. I am using the open weather map api. The error that I'm getting is GET ${forcastUrl} 404 (Not Found).
My fetch statement looks like this:
function fetchingForcast(forcastUrl){
fetch(forcastUrl)
.then(validateWeatherResponse)
.then(responseToJSON)
.then(dat => {
forcastDat = dat;
updateforcastPanel();
})
.catch(error=>{
console.log(error);
})
}
function validateWeatherResponse(response){
if (response.ok){
return response;
} else {
throw Error("response.ok: "+ response.ok);
}
validateWeatherResponse checks if the response is ok and if not, it throws an error. However, when it does throw an error, it should go to catch and console.log the error. When I use the debug devtool on chrome, the error appears to happen as soon as validateWeatherResponse is called.
Besides for this error, my code works when I input a correct website. It is to my understanding that 404 errors should not occur so I'd like to understand why this is happening.
Thanks!
From MDN's HTTP status code documentation:
404 Not Found
The server can not find the requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. This response code is probably the most famous one due to its frequent occurrence on the web.
The 404 error code means that the website or endpoint that you requested does not exist, which is definitely expected if you request a non-existent page.
If you are still confused about the error, please tell me in a comment.

How to detect if HTTP requests are blocked by a browser extension?

I am trying to detect if a user is using some kind of extension in his browser that could prevent my site from working properly and if so, display a message for the user.
I am testing with an extension called uMatrix, but there are others with a similar approach.
My problem is, that kind of extension will block my HTTP request, but that doesn't return a proper status code (like 403, 404, 500, etc). Instead, when I catch my request, I just get a
Error: Network Error
at [my file name and line number here]
at XMLHttpRequest.handleError (xhr.js:83)
I believe this same error would be thrown in other circumstances, like lack of internet connection, so I can't assume this Network Error means that the user has a "HTTP request blocker".
I was reading a lot about identifying AdsBlocker on this thread and other places, but I don't think it applies to my issue.
Any ideas on how to identify that a user is blocking my HTTP Requests? (Either on purpose or through a browser extension)
I thought I would share here the solution I found, even though I don't think that's the best answer yet.
I am using Axios for my API requests and I found this thread here:
https://github.com/axios/axios/issues/383#issuecomment-234079506
What they suggest it's to check if the response has a status (but in latest Axios, they don't even return a response). If not, it means the server was never reached. That could still mean that there is no internet connection, not necessarily an extension blocked the request. So I adjusted my message to cover both scenarios.
My final code was something like this:
// Note the use of "HEAD", since that will be faster than a "GET"
axios.head(server_url_for_testing).catch(function(error) {
if (!error.response) {
// Display my warning message
}
})

Web worker importScripts DOMException script failed to load

I'm trying to use importScripts
self.addEventListener('fetch', event => {
...
self.importScripts('idb.js');
...
}
to load a library for a service worker for a PWA but keep getting
DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope':
The script at 'http://localhost:3000/idb.js' failed to load.
The script file is there, content type is correct, application/javascript, and I've tried it with text/javascript too. My developer tools network tab shows the request starting and then failing really quickly, not getting a chance to hit the server. The status code is (failed) net::ERR_CONNECTION_REFUSED when over http and (failed) net::ERR_FAILED over https. Any help appreciated
According to https://developers.google.com/web/updates/2018/10/tweaks-to-addAll-importScripts
Prior to Chrome 71, calling importScripts() asynchronously outside of the install handler would work. Starting with Chrome 71, those calls throw a runtime exception (unless the same URL was previously imported in an install handler), matching the behavior in other browsers.
I have to move importScripts to the top level of my file or my install handler and it works
Based upon the link you provided, you are not running under HTTPS. You need a site under HTTPS to use a service worker.
My original post wrong. #kmanzana pointed out that localhost is considered a "secure origin".
Also, if there is an import statement inside any of the scripts on which you are using importScripts(), you will get this error, and it will not immediately be clear why you are getting it. Caveat emptor.

xmlhttprequest - exception 101 error

requrl_1 = "http://www.example.com/index.php";
requrl_2 = "http://www.example.com/redirect.php";
when I request "requrl_1", there is no problem. I'm getting response. "index.php" is not a redirector page.
but requrl_2 is a redirector page, that is redirecting to another website(for example: http://www.cnn.com).
so when I request with XMLHttpRequest, I'm getting exception 101 error.
I must request "redirect.php", there isn't another solution.
How can I do that? Why am I getting "exception 101" error.
I'm coding a Greasemonkey userscript script for google chrome.
It's best to just install Tampermonkey and use it to run your script. Then you can code with GM_xmlhttpRequest()Doc -- which has cross-domain support. And scripts get enhanced capabilities to match what Greasemonkey can do on Firefox.
If you don't want to install Tampermonkey, Chrome userscripts now support cross-site requests via GM_xmlhttpRequest().
So, you could use:
GM_xmlhttpRequest ( {
method: "GET",
url: "http://www.example.com/redirect.php",
onload: function (response) {
//-- Do your business here.
}
} );
From the XMLHttpRequest Spec
If something goes wrong (infinite loop, network errors) the state must
be set to loaded and all members (excluding readyState) of the object
must be set to their initial value. Also, if async is set to false, a
NETWORK_ERR exception must be raised. In addition, all registered
event listeners must be removed.
Basically the redirect is causing the same origin policy to be fired. Which is firing the error. The request should be served with a proxy and not a redirect.

Categories