2

In my Rails 3.2.15 / Ruby 1.9.3p448 project I want to catch exceptions produced by 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

In case of an ArgumentError I want to implement two different behaviors:

  1. If the message matches a specific error message I want to render a custom response.
  2. In other cases I want to continue and let the generic exception block rescue from the error.
JJD
  • 50,076
  • 60
  • 203
  • 339

1 Answers1

3

This is how I would do it. Please also do not rescue from Exception for the reasons detailed here – use StandardError instead.

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
Community
  • 1
  • 1
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
  • It crashes with `TypeError - class or module required:` here `if e.is_a? ArgumentError && ..` – JJD Nov 13 '13 at 17:33
  • Works for me here on MRI 2.0.0p247. Which ruby version are you using? – Patrick Oscity Nov 13 '13 at 17:36
  • Looks like a bug in 1.9.3 to me? What do you think? – JJD Nov 15 '13 at 10:07
  • 1
    I think I might have made one of those copy-paste or refactoring-without-running-again mistakes. Now I can reproduce the error on 2.0, so my code was actually incorrect. Sorry for the confusion! – Patrick Oscity Nov 15 '13 at 20:38