【问题标题】:Could we rescue, raise and rescue the same error again using exception hierarchy syntax in ruby?我们可以使用 ruby​​ 中的异常层次结构语法再次拯救、引发和拯救同样的错误吗?
【发布时间】:2020-12-15 23:03:08
【问题描述】:

我希望使用下面的 sn-p 等异常层次结构语法来拯救、引发和再次拯救异常。

class InnerCustomError < StandardError
  def initialize(msg = "inner")
    super
  end
end

class OuterCustomError < StandardError
  def initialize(msg = "outer")
    super
  end
end

begin
  raise InnerCustomError
rescue InnerCustomError
  raise OuterCustomError
rescue OuterCustomError, StandardError => e
  e.message
end

但这会引发 ==> OuterCustomError (outer)

为什么会出现这种行为?相反,我希望它被救出..

我知道下面的嵌套开始结束块用于实现相同的目的,

begin
  begin 
    raise InnerCustomError
  rescue InnerCustomError 
    raise OuterCustomError
  end
rescue OuterCustomError, StandardError => e
  e.message
end

我也知道这个想法会影响性能,但我想了解前者是如何解释的?

【问题讨论】:

  • 否则,当(重新)从rescue 中引发异常时,您很容易陷入无限循环。
  • 顺便说一句,你想达到什么目的?仅仅为了挽救它而引发异常似乎没有多大意义。
  • 哦,这是一个非常常见的模式。在我的用例中,我有一个 API 控制器,它实际上处理所有 JTW InvalidTokenErrors* 并将其重新提升为 customError,最终将再次捕获以构建HTTP 状态 423 的错误响应阻止用户并强制客户端再次实际登录..

标签: ruby exception


【解决方案1】:

但这会引发OuterCustomError。为什么会出现这种行为?

因为这就是这个构造的工作原理。第一个匹配的rescue 被选为异常的处理程序,此处理的结果将是begin/rescue 的结果。如果处理程序引发并且您想捕获该新异常,则需要添加另一层开始/救援,就像您在上一个 sn-p 中显示的那样。

在文档here中有描述。

【讨论】:

  • 感谢您的解释。如果可能的话,您能帮我参考一下这种行为吗?
  • @Sathish 参见Exception Handling 中的第一个示例——# code that might raise 部分介于beginrescue 之间。
  • @sergio-tulentsev 我从文档here 中找到了实际参考,它解释了异常仅从顶部开始匹配一次..
  • @Sathish:啊,谢谢!如果您不介意,我会将其添加到答案中。
猜你喜欢
  • 2013-06-28
  • 1970-01-01
  • 2017-01-30
  • 2015-06-13
  • 2011-06-15
  • 2017-06-03
  • 2013-11-27
  • 1970-01-01
  • 2018-11-27
相关资源
最近更新 更多