13

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): enter image description here

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

2
  • There’s nothing at kirupa.com/book/images/learning_react2.gif so the server sends a 404 response to all clients regardless. But you prefer that browser devtools not show a 404 despite the fact that’s the actual status in the server response? Commented May 17, 2017 at 8:50
  • If this only happens in devtools then that is totally fine. That file not existing is deliberate. The 404 showing up as an error seemed a bit odd. As long as end users don't see the error, then I am not too concerned. Commented May 17, 2017 at 15:01

4 Answers 4

6

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.

Code I'm using

I tried to replicate what you're saying using the following run with http-server. There is no "data.json" file.

index.html

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

index.js

(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");
    });
}());

Dev Tools Screenshots

Chrome

Chrome Dev Tools

Firefox

Firefox Dev Tools

Safari

Safari Dev Tools

Analysis

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can try to handle the error yourself and actually trigger a Promise.reject(). Something like this

fetch("https://httpstat.us/500", {
    method: "head",
    mode: "no-cors"
})
.then(status)
.then(res => res.json())
.catch(function(error) {
    console.log("Error", error);
});

function status(response) {   
    if (response.ok) {
        return response;
    }
    return response.json().then(res => Promise.reject(res));
}

Comments

1

I would like to share this code snippet to show another way of using promise chain while fetching through an API.

<script>
let url = "https://jsonplaceholder.typicode.com/todos/1";

fetchApi(url);

function handleData(data){
  console.log('succesfull:', data)
}

function fetchApi(url){
  fetch(url)
    .then(response => response.ok ? response.json() : Promise.reject({err: response.status}))
    .then(data => handleData(data))
    .catch(error => console.log('Request Failed:', error));
}

</script>

1 Comment

Doesn't answer the question of the console logging errors
-2

You can try pass function which is called when promise is rejected. You can do that by passing second function in then

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.