I am using the fetch API with a REST API, and i want to handle certain errors globally, errors like 500, 503 ...
I tried doing something like this
function(url, method, data) {
return fetch(url, {
method: method || "GET",
body: JSON.stringify(data),
mode: "cors",
headers: {
"Content-Type": "application/json; charset=utf-8"
}
}).then(response => {
if (response.ok && response.status < 500) console.log("ouch");;
return response;
});
but it doesn't seem to be working. how do i catch 500, 503 ...
in the fetch api?
Try this approach in this way you can handle all possible errors at one place and you also can generate custom response to return e.g if your all requests return JSON data then you can convert response to JSON before returning it.
function secureFetch(url, method, data) {
return new Promise((resolve, reject) => {
fetch(url, {
method: method || "GET",
body: JSON.stringify(data),
mode: "cors",
headers: {
"Content-Type": "application/json; charset=utf-8"
}
}).then(response => {
// response only can be ok in range of 2XX
if (response.ok) {
// you can call response.json() here too if you want to return json
resolve(response);
} else {
//handle errors in the way you want to
switch (response.status) {
case 404:
console.log('Object not found');
break;
case 500:
console.log('Internal server error');
break;
default:
console.log('Some error occured');
break;
}
//here you also can thorow custom error too
reject(response);
}
})
.catch(error => {
//it will be invoked mostly for network errors
//do what ever you want to do with error here
console.log(error);
reject(error);
});
});
}
secureFetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error));
secureFetch('https://jsonplaceholder.typicode.com/posts/100000000')
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With