最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I handle error 404 in asyncawait fetch API - Stack Overflow

programmeradmin1浏览0评论

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(`.5/weather?q=${city},${country}&appid=${API_KEY}&units=metric`);

    const data = await api_call.json();

    console.log(data);
  }
<script src=".1.0/react.min.js"></script>
<script src=".1.0/react-dom.min.js"></script>

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>

Share Improve this question edited Sep 7, 2019 at 12:57 Nicolás Alarcón Rapela 2,9821 gold badge20 silver badges34 bronze badges asked Aug 10, 2018 at 7:22 PaulPaul 3461 gold badge4 silver badges17 bronze badges 3
  • 1 if (api_call.ok) { 200-299 } api_call.status contains the status code – Endless Commented Aug 10, 2018 at 7:24
  • In your screenshot the response is in the output, what do you mean by "I recevie Error 404 but can't for example console.log it" ? – gbalduzzi Commented Aug 10, 2018 at 7:30
  • Tip: use https! – Endless Commented Aug 10, 2018 at 7:37
Add a comment  | 

4 Answers 4

Reset to default 6

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

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

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

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

  }
发布评论

评论列表(0)

  1. 暂无评论