一個(gè)迭代開發(fā)中的網(wǎng)站難免存在bug,出bug的時(shí)候客戶體驗(yàn)就很不好了,為解決此問題,可以在class error產(chǎn)生的時(shí)候,觸發(fā)跳轉(zhuǎn)到統(tǒng)一提示頁(yè)面,并給開發(fā)人員發(fā)郵件報(bào)錯(cuò)誤信息,提高測(cè)試能力和用戶體驗(yàn)。以下是核心方法;在ApplicationController中添加如下代碼,不同rails版本的class error略有變化。
復(fù)制代碼 代碼如下:
AR_ERROR_CLASSES = [ActiveRecord::RecordNotFound, ActiveRecord::StatementInvalid]
ERROR_CLASSES = [NameError, NoMethodError, RuntimeError,
ActionView::TemplateError,
ActiveRecord::StaleObjectError, ActionController::RoutingError,
ActionController::UnknownController, AbstractController::ActionNotFound,
ActionController::MethodNotAllowed, ActionController::InvalidAuthenticityToken]
ACCESS_DENIED_CLASSES = [CanCan::AccessDenied]
if Rails.env.production?
rescue_from *AR_ERROR_CLASSES, :with => :render_ar_error
rescue_from *ERROR_CLASSES, :with => :render_error
rescue_from *ACCESS_DENIED_CLASSES, :with => :render_access_denied
end
#called by last route matching unmatched routes. Raises RoutingError which will be rescued from in the same way as other exceptions.
#備注rails3.1后ActionController::RoutingError在routes.rb中最后加如下代碼才能catch了。
#rails3下:match '*unmatched_route', :to => 'application#raise_not_found!'
#rails4下:get '*unmatched_route', :to => 'application#raise_not_found!'
def raise_not_found!
raise ActionController::RoutingError.new("No route matches #{params[:unmatched_route]}")
end
def render_ar_error(exception)
case exception
when *AR_ERROR_CLASSES then exception_class = exception.class.to_s
else exception_class = 'Exception'
end
send_error_email(exception, exception_class)
end
def render_error(exception)
case exception
when *ERROR_CLASSES then exception_class = exception.class.to_s
else exception_class = 'Exception'
end
send_error_email(exception, exception_class)
end
def render_access_denied(exception)
case exception
when *ACCESS_DENIED_CLASSES then exception_class = exception.class.to_s
else exception_class = "Exception"
end
send_error_email(exception, exception_class)
end