How can I handle error 404 in async/await fetch API
Just examine the status
property of the resolved promise before you try to extract the body with the .json()
method.
async function test() {
const api_call = await fetch(`https://cors-anywhere.herokuapp.com/http://example.com/fake/fake`);
console.log(api_call.status);
}
test();
Regardless of using async/await
or promise chaining, the fetch
API returns a promise
containing a Response
object. The response object contains a status
property which returns an HTTP status code. Before you call the .json()
method on your response
object you can check to see if res.status === 200
. For example, the OpenWeather API will return a HTTP status code of 200
for successful requests. So, to check if your API request was successful, you could do the following ...
class App extends React.Component{
getWeather = async (e) => {
e.preventDefault();
const city = e.target.elements.city.value;
const country = e.target.elements.country.value;
const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${API_KEY}&units=metric`);
if (api_call.status !== 200) {
// You can do your error handling here
} else {
// Call the .json() method on your response to get your JSON data
const data = await api_call.json();
}
}
You can see more of the Response
object properties and methods By viewing the MDN documentation