如何继续使用Ruby中的下一个救援块?

时间:2013-11-13 12:07:34

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

在我的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. 在其他情况下,我想继续并让通用异常块从错误中解救。

1 个答案:

答案 0 :(得分:3)

我就是这样做的。另请注意,请勿使用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