我正在开发一个 RoR 网站,希望单独处理服务器错误(400、404、500 等)。另外,由于网站是动态的,我想在 Rails 环境中处理错误,而不是在服务器级别。
我想做的一个例子是,当用户遇到无法加载或根本不存在的页面或模板时,向用户提供可选材料或搜索栏。
因此,我做了一些阅读,我认为使用rescue_from异常处理程序是我的情况的最佳选择。 (如果你们有不同的意见,我会非常高兴)。
我有一个简单的工作原型(请参阅下面的代码)并正在运行,但是,当我在代码中包含以下异常处理程序时,我收到错误:
rescue_from ActionController::MissingTemplate, :with => :not_found #404
现在,我看不到我有拼写错误,并且我在网络上发布的代码中看到了这一行。但是,当我包含它时,我收到以下路由错误:
Routing Error No route matches "/errorhandle" with {:method=>:get}
我正在开发 Rails 2.3.5,也许这与它有关?
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery #See ActionController::RequestForgeryProtection for details
#ActiveRecord exceptions
rescue_from ActiveRecord::RecordNotFound, :with => :not_found #400
#ActiveResource exceptions
rescue_from ActiveResource::ResourceNotFound, :with => :not_found #404
#ActionView exceptions
rescue_from ActionView::TemplateError, :with => :not_found #500
#ActionController exceptions
rescue_from ActionController::RoutingError, :with => :not_found #404
rescue_from ActionController::UnknownController, :with => :not_found #404
rescue_from ActionController::MethodNotAllowed, :with => :not_found #405
rescue_from ActionController::InvalidAuthenticityToken, :with => :not_found #405
rescue_from ActionController::UnknownAction, :with => :not_found #501
# This particular exception causes all the rest to fail.... why?
# rescue_from ActionController::MissingTemplate, :with => :not_found #404
protected
def not_found
render :text => "Error", :status => 404
end
# Scrub sensitive parameters from your log
# filter_parameter_logging :password
end