自定义404错误,路由错误会停止应用

时间:2012-12-25 12:16:27

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

在ApplicationController中我添加了:

class ApplicationController < ActionController::Base

# This code never reached when routing error occurs
unless Rails.application.config.consider_all_requests_local
  rescue_from ActionController::RoutingError, with: :render_404
  rescue_from ActionController::UnknownController, with: :render_404
  rescue_from ActionController::UnknownAction, with: :render_404
  rescue_from ActiveRecord::RecordNotFound, with: :render_404
end

当我试图捕获未找到页面的异常时,我注意到当触发路由错误时,上面的代码从未到达,因此,render_404从未调用

Rails.application.config.consider_all_requests_local是假的,不知道吗?

这是我得到的:

ActionController::RoutingError (No route matches [GET] "/not_there_route"):
  actionpack (3.2.5) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
  actionpack (3.2.5) lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
  railties (3.2.5) lib/rails/rack/logger.rb:26:in `call_app'
  railties (3.2.5) lib/rails/rack/logger.rb:16:in `call'
  actionpack (3.2.5) lib/action_dispatch/middleware/request_id.rb:22:in `call'
  rack (1.4.1) lib/rack/methodoverride.rb:21:in `call'
  rack (1.4.1) lib/rack/runtime.rb:17:in `call'
  activesupport (3.2.5) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
  rack (1.4.1) lib/rack/lock.rb:15:in `call'
  actionpack (3.2.5) lib/action_dispatch/middleware/static.rb:62:in `call'
  railties (3.2.5) lib/rails/engine.rb:479:in `call'
  railties (3.2.5) lib/rails/application.rb:220:in `call'
  railties (3.2.5) lib/rails/railtie/configurable.rb:30:in `method_missing'
  rack (1.4.1) lib/rack/deflater.rb:13:in `call'
  rack (1.4.1) lib/rack/content_length.rb:14:in `call'
  railties (3.2.5) lib/rails/rack/log_tailer.rb:17:in `call'
  thin (1.3.1) lib/thin/connection.rb:80:in `block in pre_process'
  thin (1.3.1) lib/thin/connection.rb:78:in `catch'
  thin (1.3.1) lib/thin/connection.rb:78:in `pre_process'
  thin (1.3.1) lib/thin/connection.rb:53:in `process'
  thin (1.3.1) lib/thin/connection.rb:38:in `receive_data'
  eventmachine (0.12.10) lib/eventmachine.rb:256:in `run_machine'
  eventmachine (0.12.10) lib/eventmachine.rb:256:in `run'
  thin (1.3.1) lib/thin/backends/base.rb:61:in `start'
  thin (1.3.1) lib/thin/server.rb:159:in `start'
  rack (1.4.1) lib/rack/handler/thin.rb:13:in `run'
  rack (1.4.1) lib/rack/server.rb:265:in `start'
  railties (3.2.5) lib/rails/commands/server.rb:70:in `start'
  railties (3.2.5) lib/rails/commands.rb:55:in `block in <top (required)>'
  railties (3.2.5) lib/rails/commands.rb:50:in `tap'
  railties (3.2.5) lib/rails/commands.rb:50:in `<top (required)>'

1 个答案:

答案 0 :(得分:2)

你应该添加catch all route,如下所示:

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

此处更详细http://www.bdunagan.com/2012/04/27/rescue_from-routingerror-in-rails-3/