【问题标题】:ruby on rails 3.1 global exception handlerruby on rails 3.1 全局异常处理程序
【发布时间】:2011-12-13 19:42:24
【问题描述】:

我正在使用 Rails 3.1.2 开发应用程序,但在此版本的 rails 上找不到一些适用于错误/异常(如 404)的文档。

我尝试过类似的方法:

在应用程序控制器中

rescue_from ActiveRecord::RecordNotFound,ActionController::RoutingError, 
             ActionController::UnknownController, ActionController::UnknownAction, :NoMethodError, :with => :handle_exception 

  def handle_exception 
   render :template => 'error_pages/error'
  end 

environment/development.rb

config.consider_all_requests_local = false

我在哪里可以找到解决方案?

提前谢谢...

【问题讨论】:

    标签: ruby exception-handling ruby-on-rails-3.1


    【解决方案1】:

    这应该有效:

    在应用程序控制器中

      class NotFound < StandardError; end
      rescue_from NotFound, :with => :handle_exception
    
      def handle_exception 
       render :template => 'error_pages/error'
      end
    

    【讨论】:

    • 只想补充:用"end"代替"end"好像无效。
    【解决方案2】:

    action_dispatch/middleware/show_exceptions

    来自源中的文档:

    # This middleware rescues any exception returned by the application
    # and wraps them in a format for the end user.
    

    简而言之,当包装的应用程序(Rails,在您的情况下)遇到未获救的异常时,它会呈现 ActionDispatch::ShowExceptions.render_exception

    如果您查看默认实现,它最终会呈现类似public/500.html 的内容,这就是您在生产环境中看到的内容。覆盖您认为合适的方法或方法链以添加您自己的实现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-17
      • 2012-12-31
      • 2011-05-19
      • 2011-08-31
      相关资源
      最近更新 更多