Quantcast
Channel: Active questions tagged return-value - Stack Overflow
Viewing all articles
Browse latest Browse all 228

How to ignore a JavaScript fetch error and return null instead?

$
0
0

I asked the Stack Overflow AI already: link, but I didn't found the answer helpful.

My question is: I want to fetch other content with JavaScript, but return null if a 404 error occurs.

Example:

function fetchJsonResultsOrNull(index) {    return fetch('headlines-'+ index +'.json')        .then(function (response) {            if (response.status == 200) {                return response.json();            }            throw new Error('Network response was not ok.');        })        .then(function (json) {            return json.results;        })        .catch(function (error) {            console.log('Fetch error:', error);            return null;        });}(async function test() {    let jsonOrNull = await fetchJsonResultsOrNull(1);    console.log(jsonOrNull); // is correctly null or json, but the webbrowser still reports an error in the console})();

but in the browser console still the 404 error occurs.


Viewing all articles
Browse latest Browse all 228

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>