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:
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