Javascript 承诺中的错误处理(抛出错误)

Error handling in Javascript promises(throwing errors)

我想对从我正在进行的调用收到的响应做一些错误处理,然后在特定的空检查被命中时转移到 catch。像这样:

    fetch('example.json')
        .then(response => {
            if (response.data === null) {
                //go to catch
            }
        })
        .catch(error => {
            console.error("error happened", error);
        })

做这样的事情最好的方法是什么?在 then 块内抛出错误的任何危险信号?

如果您 throw 在一个 promise 处理程序中,则拒绝处理程序 returns 的 promise。所以:

fetch('example.json')
    .then(response => {
        if (response.data === null) {
            throw new Error();
        }
    })
    .catch(error => {
        console.error("error happened", error);
    })

您抛出的将是 catch 处理程序看到的拒绝原因。它 没有 成为 Error,但与同步代码一样,通常最好是

但是,请注意 A) A fetch response 没有 data 属性,并且 B ) 您需要检查 HTTP 是否成功并解析返回的 JSON。

你可能想要这样的东西:

fetch('example.json')
    .then(response => {
        if (!response.ok) {
            // (I tend to use an specialized `Error` type here
            // More on my anemic blog:
            // http://blog.niftysnippets.org/2018/06/common-fetch-errors.html)
            throw new Error("HTTP error " + response.status);
        }
        return response.json();
    })
    .then(data => {
        if (data === null) {
            throw new Error("The data is null");
        })
        // ...do something with `data`...
    })
    .catch(error => {
        console.error("error happened", error);
    });

在对您提出的问题的评论中:

i was hoping there was a way to check this response object without having to trigger the 'extreme' measure of throwing an exception

您确实有一个替代方案,其结果基本相同:Return 一个被拒绝的承诺。这是我上面改编的第二个代码块:

fetch('example.json')
    .then(response => {
        if (!response.ok) {
            // (I tend to use an specialized `Error` type here
            // More on my anemic blog:
            // http://blog.niftysnippets.org/2018/06/common-fetch-errors.html)
            return Promise.reject(new Error("HTTP error " + response.status));
        }
        return response.json();
    })
    .then(data => {
        if (data === null) {
            return Promise.reject(new Error("The data is null"));
        })
        // ...do something with `data`...
    })
    .catch(error => {
        console.error("error happened", error);
    });

throw 版本一样,您 不必 使用 Error,这只是最佳实践。它可以是任何你想要的。

如果需要,您可以从 promise 处理程序中抛出一个 Error 对象。

fetch('example.json')
  .then(response => {
    if (response.data === null) {
      throw new Error('oopsie');
    }
  })
  .catch(error => {
    console.error("error happened", error); // will show "Error: oopsie"
  })