大家都知道想在Rails下自定义错误显示的页面是修改 rescue_action_in_public 这个方法,我之前也写过一篇blog介绍在Rails 2.X下如何自定义错误信息页面 [url]http://yangzhihuan.iteye.com/blog/577624[/url]
不过在 Rails 3中这个方法的位置改变了,上文提到的链接中的方法已经无效了,其它还是修改 rescue_action_in_public 这个方法,只不过这个方法不再放在 ActionController::Rescue 这个module里面了,请看代码:
不过在 Rails 3中这个方法的位置改变了,上文提到的链接中的方法已经无效了,其它还是修改 rescue_action_in_public 这个方法,只不过这个方法不再放在 ActionController::Rescue 这个module里面了,请看代码:
#以下的代码放在 config/initializers 文件夹下,随便弄个文件名都可以,放在这个文件夹下,启动项目时会自动加载,这样就不用像放在 lib 文件夹中,还要手工去加载了。
module ActionDispatch
class ShowExceptions
private
# customize error handle
def rescue_action_in_public_with_handle_system_error(exception)
logger.error("rescue_action_in_public executed")
begin
# 修改这个文件的主要目的就是为了加上这么一句
SystemErrorNotify.system_error(exception).deliver
rescue => e
logger.error "****************************"
logger.error "#{e.message}"
logger.error "#{e.backtrace.join('\n')}"
logger.error "****************************"
end
# 调用原来的 rescue_action_in_public 方法,该干嘛干嘛去
rescue_action_in_public_without_handle_system_error(exception)
end
alias_method_chain :rescue_action_in_public,:handle_system_error
end
end
#注意 rescue_action_in_public 现在放在 ActionDispatch::ShowExceptions 中
# 我也不再直接覆盖 rescue_action_in_public 方法,而是使用了 alias_method_chain ,我觉得这样做扩展更加干净。