可能在Rails控制器中渲染和引发异常? [英] Possible to render and raise exception in Rails controller?

查看:181
本文介绍了可能在Rails控制器中渲染和引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经和这个战斗了几个小时了。我有一个控制器动作,我想渲染页面,然后自动引发异常。



下面是可能的吗?

  class UsersController< ActionController :: Base 

def new
#.. do stuff
begin
UserMailer :: send_confirmation_link(@user)
rescue StandardError => e
呈现'email_error'
raise(e)
end
#..其他东西
end

end

在这种情况下,我只想通知最终用户错误,然后在应用程序本身引发异常。请注意,我不能更改事实上的错误页面,因为这是具有较大应用程序的相同代码库中的较小应用程序。

解决方案



Rails既提供静态的 500.html public 这是默认情况下为异常呈现的消息,您可以自定义用户在所有异常情况下看到的消息。



还有一个 rescue_from 方法,您可以使用它来定制特定异常类的响应,这是一个很好的方式来拥有一个中心点(通常在 ApplicationController )中,异常响应都位于。



如果您正在使用您的用例,可能需要你自己的自定义异常类,一个 RuntimeError 的子类,你可以将这个异常包装在重新加载中,如:

  rescueErrorError => e 
raise EmailConfirmationError.new e.message
end

...和然后在您的 ApplicationController 中:

  rescue_from EmailConfirmationError {| e |呈现email_error} 


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.

解决方案

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" }

这篇关于可能在Rails控制器中渲染和引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆