I want to use async/awayt syntax, Fetch API and want to achieve the following behavior:
if the response is not 200, log the response, don't throw anything and return null. if the response is 200, return the response.
But! Fetch API throws an exception for everything that is different from 404, 505 or 200 and in the end I get an ugly construction like this:
...
try{
let response = await fetch(url, {method: 'GET', mode: 'cors'});
if(response.status != 200){
console.log('Failed to get what I want, got status: ' + response.status);
return null;
}
catch(e){
console.log('error bla bla');
return null;
}
...
Is there a more elegant way to achieve the same?
Fetch does not throw based on status code. It will throw if there's a network error such as not being able to reach the server. This is defined in the Fetch spec.
Here's an example of getting various status codes from Fetch
async function getit(status) {
let url = 'https://httpstat.us/' + status
try {
let response = await fetch(url, {
method: 'GET',
mode: 'cors'
});
if (response.ok) {
console.log("Got what we wanted")
} else {
console.log('Failed to get what I want, got status: ' + response.status);
}
return "okay";
} catch (e) {
console.log('A real error!');
return "network error";
}
}
getit(200).then(console.log)
// error codes
getit(400).then(console.log)
getit(503).then(console.log)
getit(401).then(console.log)
So long as it receives an HTTP response, it should not throw.
(You do have a typo in your code — you're missing the closing bracket on the if (response.status != 200) {
, but this should cause a syntax error not a rejected promise)