Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle error 404 in async/await fetch API

Is there any opurtinity to catch Error where there will be no data provided? I recevie Error 404 but can't for example console.log it...

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`);

    const data = await api_call.json();

    console.log(data);
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Image error from Browser

like image 622
Paul Avatar asked Aug 10 '18 07:08

Paul


People also ask

Does fetch throw error 404?

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 (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

Does fetch support async await?

fetch() starts a request and returns a promise. When the request completes, the promise is resolved with the Response object. If the request fails due to some network problems, the promise is rejected. async/await syntax fits great with fetch() because it simplifies the work with promises.


4 Answers

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

like image 181
Angelo Bovino Avatar answered Oct 06 '22 17:10

Angelo Bovino


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();
like image 34
Quentin Avatar answered Oct 06 '22 18:10

Quentin


Try try catch:

getWeather = async (e) => {
    try {
        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`);
        const data = await api_call.json();
        console.log(data);
    } catch(e) {
        console.log('error: ', e);  
    }
}
like image 20
Faly Avatar answered Oct 06 '22 17:10

Faly


Use

class App extends React.Component{
  getWeather = async (e) => {
    e.preventDefault();

    const city = e.target.elements.city.value;
    const country = e.target.elements.country.value;
    try {
        const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${API_KEY}&units=metric`);

        const data = await api_call.json();
        console.log(data);
    } catch(e) {
       console.log(e);
    }

  }
like image 38
Jasmin Mistry Avatar answered Oct 06 '22 17:10

Jasmin Mistry