【问题标题】:Rescuing errors in Rails 3.2 with `config.exceptions_app = self.routes`使用 `config.exceptions_app = self.routes` 修复 Rails 3.2 中的错误
【发布时间】:2012-10-25 22:17:18
【问题描述】:

根据这篇文章:

http://blog.plataformatec.com.br/2012/01/my-five-favorite-hidden-features-in-rails-3-2/

最新的错误处理方式如下:

# application.rb:
config.exceptions_app = self.routes

#routes.rb
match "/404", to: "site#not_found"

但是,他没有解决 Rails 错误应用程序还处理 500 个错误、422 个错误(以及可能会流入这两个页面的其他错误?)这一事实?

所以我拼凑了一个看起来像这样的解决方案:

# routes.rb
rack_error_handler = ActionDispatch::PublicExceptions.new('public/')
match "/422" => rack_error_handler
match "/500" => rack_error_handler

这很好,因为它使我的 500 页保持轻量级。

还有其他我应该捕捉的错误吗? 我的理解是,虽然 500 页面现在将使用两个机架应用程序,但它仍然足够安全地与主 Rails 应用程序隔离。这么强吗?

谢谢!

【问题讨论】:

标签: ruby-on-rails routing


【解决方案1】:

我在应用程序控制器中添加了救援来源

  if Rails.env.production?
    rescue_from ActiveRecord::RecordNotFound, :with => :render_not_found
    rescue_from ActionController::RoutingError, :with => :render_not_found
    rescue_from ActionController::UnknownController, :with => :render_not_found
    rescue_from ActionController::UnknownAction, :with => :render_not_found
    rescue_from ActionView::MissingTemplate, :with => :render_not_found
  end

  def render_not_found(exception)
    logger.info("render_not_found: #{exception.inspect}")
    redirect_to root_path, :notice => 'The page was not found.'
  end

然后添加一个 errors_controller 来挽救路由错误,并将其添加到我的路由文件的底部

  match "*path", :to => "errors#routing_error"

【讨论】:

  • 请注意,rescue_from 块接受参数数组,进一步简化:code-worrier.com/blog/error-pages-in-rails
  • 最后的比赛所有路线对我来说似乎太骇人听闻了..没有冒犯但有什么想法吗?
【解决方案2】:

试试这个

更新config/application.rb

config.exceptions_app = self.routes

还有你的路由文件

match "/404", :to => "errors#not_found"

【讨论】:

    猜你喜欢
    • 2018-01-30
    • 2015-04-21
    • 2012-08-02
    • 2023-01-24
    • 2013-05-20
    • 1970-01-01
    • 2023-04-03
    • 2012-07-03
    • 1970-01-01
    相关资源
    最近更新 更多