Search code examples
javascriptgoogle-chromewebconsole

fetching from a URL shows an error in console even after catching it?


Suppose, I have this function with a wrong 'uri' string provided to fetch:

function imgChanger(uri) {
    fetch('uri', { mode: 'cors' })//WRONG 'uri' to demonstrate that catch doesn't prevent console's red error
        .then(function (response) {
            if (!response.ok) {
                throw new Error(response.statusText);
            }
            return response.json();
        }).then(function (response) {
            img.src = response.data.images.original.url;
        }).catch((err)=>{
            console.log(err);
        });
}

Despite handling the error, I can see a 404 message in the console:

enter image description here

I have two questions regarding this: why is it being shown despite catching it and how do I handle it?


Solution

  • I'm afraid there's little you can do here. There's an Issue 124534: Provide a way not to display 404 XHR errors in console open in Chromium almost 10 (!) years ago:

    Chromium always displays HTTP 404s as errors in the Javascript console. Apart from forcing line noise onto developers when they may not want it (404s can be spotted easily in the 'Network' tab), I think this actually goes against the spirit of HTTP. If you have a telephone direcotry lookup, for example, and you GET http://myHost/directory/numbers/12345678

    ... the server should respond with a 404 if that number was not in the directory. This is even really an 'error' in my opinion - it's just information. Why should Chromium display this as an error in the console?

    And as you can see, it's still open (and is essentially treated as 'by design'). Here's another telling quote:

    8 years gone by and I still cannot control how a client responds to a request. Our in-house API's have been changed to always respond with 200, with a custom status field to correctly filter what is an actual error and what is just simply not there.

    It's painfully moronic that we have to move away from REST to actually use a semantic status.

    But rejoice! there seems to be a discussion open in 2021, so hopefully we'll get things moving in the end. Now, unfortunately, it's not that easy:

    There seems to be general agreement that it would be preferable to remove these error messages from the console. But it is also very likely that currently a lot of DevTools users depend on these error messages in their workflow. We have not yet found a way to reconcile these 2 sides.

    And now the obligatory xkcd comic:

    enter image description here