ruby-on-rails - 捕获所有类型的错误并在Rails 4中呈现404页面

标签 ruby-on-rails ruby error-handling

我的代码在这里

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  #before_filter :session_must_exist
  protect_from_forgery with: :exception

  helper_method :current_user, :back_url, :parent_url
  unless Rails.application.config.consider_all_requests_local
    rescue_from Exception, :with => :method_missing
    rescue_from ActiveRecord::RecordNotFound, :with => :method_missing
    rescue_from AbstractController::ActionNotFound, :with => :method_missing
    rescue_from ActionController::RoutingError, :with => :method_missing
    rescue_from ActionController::UnknownController, :with => :method_missing
    rescue_from ActionController::UnknownAction, :with => :method_missing
  end

  def method_missing(m, *args, &block)
    Rails.logger.error(m)
    redirect_to :controller=>"errors", :action=>"error_404"
    render/redirect_to somewhere else
  end
end

但这对我不起作用。它给了我们
AbstractController::ActionNotFound (The action 'show' could not be found for BuildInstallersController):
  actionpack (4.0.0) lib/abstract_controller/base.rb:131:in `process'
  actionpack (4.0.0) lib/abstract_controller/rendering.rb:44:in `process'
  actionpack (4.0.0) lib/action_controller/metal.rb:195:in `dispatch'
  actionpack (4.0.0) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
  actionpack (4.0.0) lib/action_controller/metal.rb:231:in `block in action'
  actionpack (4.0.0) lib/action_dispatch/routing/route_set.rb:80:in `call'
  actionpack (4.0.0) lib/action_dispatch/routing/route_set.rb:80:in `dispatch'
  actionpack (4.0.0) lib/action_dispatch/routing/route_set.rb:48:in `call'
  actionpack (4.0.0) lib/action_dispatch/journey/router.rb:71:in `block in call'
  actionpack (4.0.0) lib/action_dispatch/journey/router.rb:59:in `each'
  actionpack (4.0.0) lib/action_dispatch/journey/router.rb:59:in `call'
  actionpack (4.0.0) lib/action_dispatch/routing/route_set.r

最佳答案

问题在于,result_from仅从 Controller 内发生的异常中解救,而AbstractController::ActionNotFound是路由问题,因此在实例化 Controller 之前引发它。

您应该能够使用以下方法做您需要做的事情:

match '*a', :to => 'errors#error_404'

添加为路线的最后一行。

但是,最优雅的解决方案是像这样利用exception_apps:
# your environment file
config.exceptions_app = ->(env) { ErrorsController.action(:error_404).call(env) }

关于ruby-on-rails - 捕获所有类型的错误并在Rails 4中呈现404页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23493115/

相关文章:

ruby-on-rails - 有没有办法让 "rake routes"看起来更好?

ruby-on-rails - 修复错误 Gem Load Error is : uninitialized constant when run a gem in project

ruby 双问号

swift - 在没有向下转换错误的情况下处理 Swift 4.2 中的错误

php - 输入错误内联

ruby-on-rails - 具有多个参数的 Rake 执行

mysql - 具有 2 个不同可连接条件的 Ruby 查询

ruby-on-rails - 如何将模型导入自定义 rake 任务?

ruby-on-rails - 无法找到 Rails/Heroku : "The page you were looking for doesn' t exist"的解决方案

r - 导致计算错误的数据集大小