如何处理异步/等待获取API中的错误404

Pau*_*aul 5 javascript async-await reactjs fetch-api

如果没有数据,有没有发现错误的机会?我收到错误404,但无法通过console.log例如...

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);
  }
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

来自浏览器的图像错误

Ang*_*ino 6

无论使用async/await还是 Promise 链,fetchAPI 都会返回一个promise包含Response对象。响应对象包含status一个返回 HTTP 状态代码的属性。在调用对象.json()的方法之前response,您可以检查一下if res.status === 200。例如,OpenWeather API 将返回200成功请求的 HTTP 状态代码。因此,要检查您的 API 请求是否成功,您可以执行以下操作...

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();
    }
  }
Run Code Online (Sandbox Code Playgroud)

您可以通过查看 MDN 文档来查看更多Response对象属性和方法


Fal*_*aly 1

尝试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);  
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个返回了我之前遇到的相同错误 (3认同)