我的代码在这里
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/