在 fetch() 函数中捕获错误

问题描述 投票:0回答:1

最近学习了一些关于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);
   })

谢谢你!

javascript error-handling fetch-api es6-promise
1个回答
6
投票

利用承诺处理程序链接在一起的事实。每次调用 then

catch
 都会创建一个新的 Promise,该 Promise 链接到前一个 Promise。

所以在你的情况下:

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

我假设如果

parseRooms

 接收到的结构有问题,它会抛出错误。

您可能还想检查其中的

res.ok

,因为 
fetch
 仅在出现网络错误时才会 
fails,而不是在出现 404 等 HTTP 错误时才会出现:

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 });
    
© www.soinside.com 2019 - 2024. All rights reserved.