簡體   English   中英

如何在async / await fetch API中處理錯誤404

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

是否有任何opurtinity捕獲錯誤,沒有提供數據? 我接收錯誤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); } 
 <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> 

瀏覽器中的圖像錯誤

在嘗試使用.json()方法提取主體之前,只需檢查已解析的promise的status屬性。

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

使用

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

  }

無論使用async/await還是promise chaining, fetch API都會返回包含Response對象的promise 響應對象包含status屬性,該屬性返回HTTP狀態代碼。 response對象上調用.json()方法之前,您可以檢查if res.status === 200 例如,OpenWeather API將為成功請求返回HTTP狀態代碼200 因此,要檢查您的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();
    }
  }

您可以通過查看MDN文檔來查看更多Response對象屬性和方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM