Как продолжить следующий спасательный блок в Ruby?

В моем проекте 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 ответ

Решение

Вот как бы я это сделал. Пожалуйста, также не спасайте от Exception по причинам, указанным здесь - используйте 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
Другие вопросы по тегам