function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
// then use as below
fetch("http://httpstat.us/500")
.then(handleErrors)
.then(response => console.log("ok") )
.catch(error => console.log(error) );
function CheckError(response) {
if (response.ok) {
return response.json();
} else {
throw Error(response.statusText);
}
}
// Now call the function inside fetch promise resolver
fetch(url)
.then(CheckError)
.then((jsonResponse) => {
}).catch((error) => {
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Test Page</h1>
<!-- https://youtu.be/YJ7ZgGnhN5k by Steve Griffith -->
<script>const root = 'http://jsonplaceholder.typicode.com';//url for fetch
let id = Math.floor(Math.random() * 20) + 1;//random number. If >10, an error will be received, otherwise the data will be logged to the console
let uri = root + '/users/' + id;
console.log('Fetch: ', uri);
fetch(uri).then(function (response) {
if (response.status == 200) {
return response.json();
}
else { throw new Error('Number is greater than 10') }
}).then((data) => {
console.log(data);
let jsonData = JSON.stringify(data);
console.log(jsonData);
}).catch((err) => {
console.log("Error: ", err.message);
});</script>
</body>
</html>