Rails中遇到錯(cuò)誤跳轉(zhuǎn)到統(tǒng)一提示錯(cuò)誤頁的方法
一個(gè)迭代開發(fā)中的網(wǎng)站難免存在bug,出bug的時(shí)候客戶體驗(yàn)就很不好了,為解決此問題,可以在class error產(chǎn)生的時(shí)候,觸發(fā)跳轉(zhuǎn)到統(tǒng)一提示頁面,并給開發(fā)人員發(fā)郵件報(bào)錯(cuò)誤信息,提高測(cè)試能力和用戶體驗(yàn)。以下是核心方法;在ApplicationController中添加如下代碼,不同rails版本的class error略有變化。
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
相關(guān)文章
Ruby中創(chuàng)建字符串的一些技巧小結(jié)
這篇文章主要介紹了Ruby中創(chuàng)建字符串的一些技巧小結(jié),本文用先講解技巧然后給出代碼示例的方式列出了多種Ruby創(chuàng)建字符串方法,需要的朋友可以參考下2015-01-01Ruby使用Monkey Patch猴子補(bǔ)丁方式進(jìn)行程序開發(fā)的示例
Monkey Patch猴子補(bǔ)丁是指在程序解釋運(yùn)行時(shí)動(dòng)態(tài)添加類或模塊的做法,這里我們就來看一下Ruby使用Monkey Patch猴子補(bǔ)丁方式進(jìn)行程序開發(fā)的示例2016-05-05