【问题标题】:How to continue with the next rescue block in Ruby?如何继续 Ruby 中的下一个救援块?
【发布时间】:2013-11-26 00:45:02
【问题描述】:

在我的 Rails 3.2.15 / Ruby 1.9.3p448 项目中,我想捕获由ActionMailer 产生的异常...

begin
  if message.deliver
    render json: { message: "Message sent successfully" }, status: 201
  else
    render json: { error: "Failure sending message" }, status: 401
  end
rescue ArgumentError => e
  if e.message == "An SMTP To address is required to send a message."
    render json: { error: "Invalid recipient address" }, status: 422
  else
    # Continue with generic exception
  end
rescue Exception => e
  render json: { error: e.message }, status: 500
end

如果是ArgumentError,我想实现两种不同的行为:

  1. 如果消息与特定错误消息匹配,我想呈现自定义响应。
  2. 在其他情况下,我想继续并让通用异常阻止从错误中解救。

【问题讨论】:

  • raise "The exception with the message" 在 else 块中,以便通用异常可以捕获
  • @AbibullahRahamathulah 抱歉,这不起作用。这样我无法到达第二个救援区。

标签: ruby-on-rails ruby exception-handling actionmailer rescue


【解决方案1】:

这就是我的做法。也请不要从Exception for the reasons detailed here 中解救——请改用StandardError

begin
  if message.deliver
    render json: { message: "Message sent successfully" }, status: 201
  else
    render json: { error: "Failure sending message" }, status: 401
  end
rescue StandardError => e
  if e.is_a?(ArgumentError) && e.message == "An SMTP To address is required to send a message."
    render json: { error: "Invalid recipient address" }, status: 422
  else
    render json: { error: e.message }, status: 500
  end
end

【讨论】:

  • 它在TypeError - class or module required:这里崩溃if e.is_a? ArgumentError && ..
  • 在 MRI 2.0.0p247 上为我工作。您使用的是哪个 ruby​​ 版本?
  • 对我来说看起来像 1.9.3 中的错误?你怎么看?
  • 我想我可能犯了那些复制粘贴或重构而不再次运行的错误。现在我可以在 2.0 上重现错误,所以我的代码实际上是不正确的。很抱歉造成混乱!
  • 啊。感谢您的研究。
猜你喜欢
  • 2012-02-26
  • 2023-01-13
  • 1970-01-01
  • 2014-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-07
  • 1970-01-01
相关资源
最近更新 更多