Reputation: 13
I'm fetching data from an API in that way, and I'm trying to catch an 404 error on it if the user search for a invalid city but is not working.
const search = evt => {
if (evt.key === "Enter") {
fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
.then(res => res.json())
.then(result => {
setWeather(result);
setQuery('');
}).catch(() => console.log("error"));
}
}
Upvotes: 1
Views: 328
Reputation: 17805
As mentioned the docs
, since fetch
doesn't do a catch on 404
or 500
status, you can mimic the behavior by throwing an error and catching in the catch
section.
fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
.then((response) => {
if(response.status == 404){
throw '404 page not found';
}
return response.json();
})
.then((response) => {
console.log('your JSON string ',response);
})
.catch((err) => {
console.error(err);
});
Upvotes: 1
Reputation: 13
I was able to get the error that way:
const search = evt => {
if (evt.key === "Enter") {
fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
.then(res => res.json())
.then(result => {
setWeather(result);
setQuery('');
}).then((data) => {
if (data === undefined) {
alert("City not found");
}
});
}
}
Upvotes: 0
Reputation: 31805
Your code works well, as you can see:
const search = evt => {
if (evt.key === "Enter") {
fetch('http://dfsdfsdfdsfsdfdfs.com')
.then(res => res.json())
.catch(() => console.log("error"));
}
}
search({key : 'Enter'});
But an error code from the server is not considered as an error with fetch
so you have to parse the response yourself and react accordingly.
You can use res.ok
that will return true if the status code is in the 200-299 range. For more information you can check the Response object documentation
Upvotes: 1
Reputation: 1938
See the documentation: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
The Promise returned from
fetch()
won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (withok
status set to false), and it will only reject on network failure or if anything prevented the request from completing.
You have to use the response parameter provided by .then(response => {...})
and check response.ok
or response.status
to get an 404 (or 500) error.
Upvotes: 1