I'm playing around with fetch
, and I noticed that only Chrome displays an error when a resource I am fetching doesn't exist (aka a 404):
Both Edge and Firefox don't do that, and 404 errors using fetch don't seem to trigger a NetworkError to have my catch error handler to get notified. What should I do to avoid this error in Chrome?
In case you need this, my full code looks as follows:
fetch("https://www.kirupa.com/book/images/learning_react2.gif", {
method: "head",
mode: "no-cors"
})
.then(function(response) {
if (response.status == 200) {
console.log("file exists!");
} else {
console.log("file doesn't exist!");
}
return response.text();
})
.catch(function(error) {
console.log("Error ", error);
});
Thanks, Kirupa
only Chrome displays an error when a resource I am fetching doesn't exist (aka a 404)
I'm seeing this as an error in Firefox, Chrome, and Safari.
I tried to replicate what you're saying using the following run with http-server
. There is no "data.json" file.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Async Test</title>
<script src="index.js"></script>
</head>
<body>
<main>
<h1>Async Test</h1>
</main>
</body>
</html>
(async function() {
let a;
try {
a = await fetch("./data.json", {
method: "head"
});
console.log("No error");
} catch (err) {
console.log("Caught an error");
}
console.log(a);
}());
(function() {
fetch("./data.json", {
method: "head"
})
.then(data => {
console.log("No error");
console.log(data);
})
.catch(err => {
console.log("Caught an error");
});
}());
The only way for the browser to know whether the resource exists is to actually make the network request. Chrome always logs network request errors like 404. It's why you probably see a lot of errors about favicons when a site you visit doesn't have one.
You can't force your client to not see them with your own code, but a user can opt in to have the error not show up for them by changing their own browser settings. See this answer to Suppress Chrome 'Failed to load resource' messages in console.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With