在承诺捕获中重新抛出错误 [英] Rethrowing error in promise catch

查看:52
本文介绍了在承诺捕获中重新抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个教程中找到了以下代码:

I found the following code in a tutorial:

promise.then(function(result){
    //some code
}).catch(function(error) {
    throw(error);
});

我有点困惑:catch 调用有什么作用吗?在我看来它没有任何效果,因为它只是抛出与捕获到的相同的错误.我基于常规 try/catch 的工作原理.

I'm a bit confused: does the catch call accomplish anything? It seems to me that it doesn't have any effect, since it simply throws the same error that was caught. I base this on how a regular try/catch works.

推荐答案

当你展示的时候,赤裸裸的接球投掷是没有意义的.除了添加代码和缓慢执行之外,它没有做任何有用的事情.所以,如果你要 .catch() 并重新抛出,你应该在 .catch() 中做一些事情,否则你应该删除.catch() 完全.

There is no point to a naked catch and throw as you show. It does not do anything useful except add code and slow execution. So, if you're going to .catch() and rethrow, there should be something you want to do in the .catch(), otherwise you should just remove the .catch() entirely.

一般结构的通常点是当您想要在 .catch() 中执行某些内容时,例如记录错误或清理某些状态(例如关闭文件),但您想要承诺链继续被拒绝.

The usual point for that general structure is when you want to execute something in the .catch() such as log the error or clean up some state (like close files), but you want the promise chain to continue as rejected.

promise.then(function(result){
    //some code
}).catch(function(error) {
    // log and rethrow 
    console.log(error);
    throw error;
});

在教程中,它可能只是为了向人们展示他们可以在哪里捕获错误或教授处理错误然后重新抛出错误的概念.

In a tutorial, it may be there just to show people where they can catch errors or to teach the concept of handling the error, then rethrowing it.

捕获和重新抛出的一些有用的原因如下:

Some of the useful reasons for catching and rethrowing are as follows:

  1. 您想记录错误,但将承诺链保留为被拒绝.
  2. 您希望将错误转化为其他错误(通常是为了在链的末尾更容易处理错误).在这种情况下,您将重新抛出一个不同的错误.
  3. 您希望在承诺链继续之前进行一系列处理(例如关闭/释放资源),但您希望承诺链一直被拒绝.
  4. 如果出现故障,您希望 在承诺链中的这一点为调试器设置断点.
  5. 您希望处理一个特定的错误或一组错误,但重新抛出其他错误,以便它们传播回调用者.
  1. You want to log the error, but keep the promise chain as rejected.
  2. You want to turn the error into some other error (often for easier error processing at the end of the chain). In this case, you would rethrow a different error.
  3. You want to do a bunch of processing before the promise chain continues (such as close/free resources) but you want the promise chain to stay rejected.
  4. You want a spot to place a breakpoint for the debugger at this point in the promise chain if there's a failure.
  5. You want to handle a specific error or set of errors, but rethrow others so that they propagate back to the caller.

但是,在 catch 处理程序中没有其他代码的情况下,简单地捕获并重新抛出相同的错误对代码的正常运行没有任何帮助.

But, a plain catch and rethrow of the same error with no other code in the catch handler doesn't do anything useful for normal running of the code.

这篇关于在承诺捕获中重新抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆