Rails全局处理Error

好久不写了,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源码看来很有好处。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值