簡體   English   中英

在fetch()函數中捕獲錯誤

[英]Catching error in fetch() function

我最近學到了一些關於fetch()和promise的知識,現在我需要在項目中使用它。 在這里,我有一個fetch()函數,該函數很好用,但是我認為它必須捕獲一個錯誤。 那么,在fetch()函數中捕獲錯誤的最佳方法是什么? 而且我需要在then()中抓住它們? 這里有一些代碼:

const endpoint = 'http://localhost:3030/api/hotels';
const promise = fetch(endpoint)
   .then(res => res.json(), err => {
      console.log(err);
   })
   .then(parseRooms, err => {
      console.log(err);
   })

謝謝 !

利用Promise處理程序鏈接在一起的事實。 每次對thencatch調用都會創建一個新的Promise,該Promise鏈接到前一個。

因此,在您的情況下:

const promise = fetch(endpoint)
    .then(res => res.json())
    .then(parseRooms)
    .catch(error => {
        // Do something useful with the error
    });

我假設那里的parseRooms一個錯誤,如果它接收的結構有問題。

您可能也想在其中檢查res.ok ,因為只有在出現網絡錯誤時, fetch才會失敗 ,而在404錯誤等HTTP錯誤的情況下, fetch 失敗

const promise = fetch(endpoint)
    .then(res => {
        if (!res.ok) {
            throw new Error(); // Will take you to the `catch` below
        }
        return res.json();
    })
    .then(parseRooms)
    .catch(error => {
        // Do something useful with the error
    });

暫無
暫無

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

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