ruby-on-rails - rescue_from ActionController::RoutingError 不起作用

标签 ruby-on-rails ruby-on-rails-4

我试图从 ActionController::RoutingError 营救我无法让它工作。我尝试了几乎所有可以在网上找到的东西,包括 rescue_from ActionController::RoutingError in Rails 4 .我有一个错误 Controller 和错误页面。我开始工作康康access deniedRecordNotFound ,但我可以解决RoutingError .

对于 cancan 我在里面使用这个 application_controller.rb

rescue_from CanCan::AccessDenied do
    render template: 'errors/error_403', status: 403
  end

我的 route 有这个:
match "/404", to: "errors#error_404", via: :all

如果我对 RoutingError 做同样的事情它不会工作。

我也试过 match '*path', :to => "errors#error_404"但我得到错误。

我该如何解决这个问题?

编辑:如果我对 RoutingError 做同样的事情至于拒绝访问:
    rescue_from ActionController::RoutingError do
       render template: 'errors/error_404', status: 404
    end

它不会工作。

最佳答案

ActionController::RoutingError当 Rails 尝试将请求与路由匹配时引发。这发生在 Rails 甚至初始化 Controller 之前 - 因此您的 ApplicationController 永远没有机会挽救异常。

相反,Rails 默认exceptions_app开始 - 请注意,这是 Rack 意义上的应用程序 - 它使用 ENV 散列和请求并返回响应 - 在这种情况下是静态 /public/404.html文件。

您可以做的是让您的 Rails 应用程序处理动态呈现错误页面:

# config/application.rb
config.exceptions_app = self.routes # a Rack Application

# config/routes.rb
match "/404", :to => "errors#not_found", :via => :all
match "/500", :to => "errors#internal_server_error", :via => :all

然后你将设置一个特定的 Controller 来处理错误页面 - 不要在你的 ApplicationController 类中这样做,因为你会添加一个 not_foundinternal_server_error所有 Controller 的方法!
class ErrorsController < ActionController::Base
  protect_from_forgery with: :null_session

  def not_found
    render(status: 404)
  end

  def internal_server_error
    render(status: 500)
  end
end

代码借自 Matt Brictson: Dynamic Rails Error Pages - 阅读全文。

关于ruby-on-rails - rescue_from ActionController::RoutingError 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37173519/

相关文章:

ruby-on-rails - 如何从 Rails 控制台列出 postgres 中的模式?

ruby-on-rails-4 - Rails ActiveRecord 4.2 自定义排序顺序

sql - Rails Postgresql 数据库查询关系名称

ruby-on-rails - 当局部变量处于局部变量时,您将如何远程附加新对象?

css - Rails 3.1 Assets 管道指纹识别

ruby-on-rails - 如何简化将多个值插入 Ruby 中的数组?

ruby-on-rails - 更新的 ruby​​ 和 rails 给 .new .update 方法带来错误

HTML/CSS 在我的 Rails 4 应用程序中表现得很奇怪(高度不可定制等)

mysql - 在 Rails 应用程序的 MySQL 数据库中使用 TimeZone 正确存储日期

ruby-on-rails - 如何在 Rails 之外使用 Rails 3 的 ActiveSupport 核心扩展