Rails统一出错页面

Rails在出错的时候会调用../actionpack/lib/action_controller/rescue.rb中的rescue_action(exception) ,只要在application.rb覆写该函数就行了,看看这个函数的源码.

protected
# Exception handler called when the performance of an action raises an exception.
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,exception将由rescue_action_locally方法进行处理,否则由rescue_action_in_public方法处理.如下,将出错页面定向到自定义的页面.

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?
render :file => "#{RAILS_ROOT}/public/dev_error.html.erb"
else
render :file => "#{RAILS_ROOT}/public/pub_error.html.erb"
end
end