Question

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.
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top