注册 | 登录 忘记密码? 51cto首页 | 博客 | 论坛 | 招聘
热点文章 [业内传闻]今天,7月25日..
 帮助

Rails全局处理Error


2008-01-28 18:36:56
 标签:error rails handle   [推送到技术圈]

版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://blackanger.blog.51cto.com/140924/61000
好久不写了,blog密码差点忘掉。。。

网上有好多处理error的方法,新建一个controller,修改route可以自定义统一的error处理页面。下面我有个方法,和大家分享一下:

查看Rails源码 :actionpack/lib/action_controller/rescue.rb:


def rescue_action_in_public(exception) #:doc:
     render_optional_error_file response_code_for_rescue(exception)
end

我们可以重写这个方法,application.rb中:
def rescue_action_in_public(exception)
    case exception.class.name
    when
'ActiveRecord::RecordNotFound','::ActionController::UnknownAction','::ActionController::RoutingError'
         RAILS_DEFAULT_LOGGER.error("404 displayed")
         render(:file => "#{RAILS_ROOT}/public/404.html", :status => "404 Error")
     else
        RAILS_DEFAULT_LOGGER.error("500 displayed")
        render(:file => "#{RAILS_ROOT}/public/500.html", :status => "500 Error")
    end
end

然后注意,这里rescue_action_in_public方法是只对production环境有用的,在developmen模式下不起作用(这里感谢Hozaka兄弟的指教)。
我们继续看源码:
def rescue_action(exception)
    log_error(exception) if logger
    erase_results if performed?

    # Let the exception alter the response if it wants.
    # For example, MethodNotAllowed sets the Allow header.
     if exception.respond_to?(:handle_response!)
        exception.handle_response!(response)
     end

    if consider_all_requests_local || local_request?
      rescue_action_locally(exception)
    else
       rescue_action_in_public(exception)
    end
end

注 意最后那个if语句,这里是判断request是否来自本地的请求,当为development下,被rescue_action_locally方法处 理exception,但是我们如果在application里重写rescue_action_locally方法,就可以自由的测试开发了。如下:

#for development
def rescue_action_locally(exception)
    case exception.class.name
    when 'ActiveRecord::RecordNotFound','::ActionController::UnknownAction','::ActionController::RoutingError'
        RAILS_DEFAULT_LOGGER.error("404 displayed")
        render(:file => "#{RAILS_ROOT}/public/404.html", :status => "404 Error")
     else
        RAILS_DEFAULT_LOGGER.error("500 displayed")
        render(:file => "#{RAILS_ROOT}/public/500.html", :status => "500 Error")
    end
end

看Rails源码看来很有好处。


本文出自 “{ :Alex Space => " Ruby Notes " }” 博客,请务必保留此出处http://blackanger.blog.51cto.com/140924/61000





    文章评论
 
2008-01-29 09:32:27
恩 这个方法不错 支持了

 

发表评论

昵   称:
验证码:  点击图片可刷新验证码  博客过2级,无需填写验证码
内   容: