fetch()函数中的捕获错误

Арт*_*нко 1 javascript error-handling fetch es6-promise fetch-api

我最近学到了一些关于fetch()和promise的知识,现在我需要在项目中使用它.这里我有一个fetch()函数,它运行得很好,但我想,它必须捕获一个错误.那么,在fetch()函数中捕获错误的最佳方法是什么?我需要在两个()中捕获它们?这里有一些代码:

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

谢谢 !

T.J*_*der 5

使用承诺处理程序链接在一起的事实.每次调用thencatch创建一个新的承诺,这个承诺链接到前一个承诺.

所以在你的情况下:

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

parseRooms如果它收到的结构有问题,我假设那里会抛出一个错误.

你可能要检查res.ok在那里,也因为fetch只有失败,如果有一个网络错误,而不是是否有一个HTTP错误,如404:

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