Possible to render and raise exception in Rails co

2019-07-30 09:05发布

I have been fighting with this for some hours now. I have a controller action that I want to render a page and then raise an exception automatically. I couldn't find much information on this that makes me think that I am looking for the wrong thing.

Is something like the below possible?

class UsersController < ActionController::Base

  def new
    # .. do stuff
    begin
      UserMailer::send_confirmation_link(@user)
    rescue StandardError => e
      render 'email_error'
      raise(e)
    end
    # .. other stuff
  end

end

In this case I simply want to inform the end-user of the error and then raise the exception on the application itself. Notice that I can't change the de-facto error page since this is a smaller application in the same codebase with a bigger application.

1条回答
贼婆χ
2楼-- · 2019-07-30 09:43

No, you either render or raise an exception, not both.

Rails does provide both the static 500.html page in public which is what's rendered by default for exceptions, you can customize the message your users see for all exceptions there.

Also there's the rescue_from method that you can use to customize the response for a specific exception class, and that's a good way to have a central spot (usually in ApplicationController) where the exception responses are all located.

If you were doing this with your use case you would probably want your own custom exception class, a subclass of RuntimeError, that you would wrap this exception in to re-raise, like:

rescue StandardError => e
  raise EmailConfirmationError.new e.message
end

...and then in your ApplicationController:

rescue_from EmailConfirmationError { |e| render "email_error" }
查看更多
登录 后发表回答