简体   繁体   English

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

[英]Error handling in Javascript promises(throwing errors)

I would like to do some error handling on the response received from a call I am making and then move to the catch if the specific null check is hit.我想对从我正在拨打的电话收到的响应进行一些错误处理,然后在特定的 null 检查被命中时转移到 catch。 Something like this:像这样:

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

What would be the best way to go about doing something like this?关于做这样的事情,go 的最佳方式是什么? Any red flags with throwing an error inside a then block?在 then 块内抛出错误的任何危险信号?

If you throw in a promise handler, that rejects the promise the handler returns.如果您throw promise 处理程序,则会拒绝处理程序返回的 promise。 So:所以:

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

What you throw will be the rejection reason the catch handler sees.您抛出的将是catch处理程序看到的拒绝原因。 It doesn't have to be an Error , but as with synchronous code, it's generally best if it is.它不一定Error ,但与同步代码一样,如果是的话通常是最好的。

But , note that A) A fetch response doesn't have a data property, and B) You need to check for HTTP success and parse the JSON that was returned.但是,请注意 A) fetch response没有data属性,并且 B) 您需要检查 HTTP 是否成功并解析返回的 JSON。

You probably want something like this:你可能想要这样的东西:

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

In a comment on the question you've said:在对您所说的问题的评论中:

i was hoping there was a way to check this response object without having to trigger the 'extreme' measure of throwing an exception我希望有一种方法可以检查此响应 object 而不必触发抛出异常的“极端”措施

You do have an alternative which is basically identical in outcome: Return a rejected promise. Here's my second code block above adapted to do that:您确实有一个结果基本相同的替代方案:返回一个被拒绝的 promise。这是我上面的第二个代码块,用于执行此操作:

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

And as with the throw version, you don't have to use an Error , it's just best practice.throw版本一样,您不必使用Error ,这只是最佳实践。 It can be anything you want.它可以是任何你想要的。

If you want, you can throw an Error object from within your promise handler.如果需要,您可以从 promise 处理程序中抛出Error object。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM