在我的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
,我想实现两种不同的行为:
答案 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