简体   繁体   中英

How to cleanly handle an expected error in fetch?

I need to query some data via a fetch() call but I am never sure whether the request will be successful, HTTP-wise: while the server is up, the URL may (legitimely) hit a non-existing page.

I would like to cleanly handle the case and my current approach is by raising an exception:

 // the URL is just an example, I did not have anything CORS-enabled (and unavailable) handy, thus the no-cors mode fetch(`https://cdnjs.com/libraries/sdfsdfsfsdfsdfsdfdf`, { mode: 'no-cors' }) .then(r => { if (!r.ok) { console.log("page does not exist") throw Error(); } // if the page exists, it will return JSON data return r.json(); }) .then(r => { console.log(r) // things with the JSON happen here }) .catch(err => null) 

I was hoping to just return after Page does not exist , but the (empty) return would then be caught by the next then() .

Is this the correct way to exit from a fetch() when the requested URL is not available?

Yes, that looks about right. I would recommend to use functions for your thens. It makes the fetch more compact and easier to read.

 const url = 'some url'; fetch(url) .then(handleErrors) .then(parseJSON) .then(update) .catch(displayErrors); function handleErrors(res){ if(!res.ok){ throw Error(`${res.status}: Couldn't load URL.`); } return res; } function parseJSON (res){ return res.json().then(function(parsedData){ return parsedData.results[0]; }) } function update (){ //do something with the data } function displayErrors(err){ console.log(err); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM