2012-02-11 93 views
1

是否有办法告诉Rails呈现自定义错误页面(例如,您在ErrorsController中编写的页面)?我已经搜查了许多话题,那似乎是一个有点儿工作是添加到您的ApplicationController如何正确呈现自定义404和500页面?

if Rails.env.production? 
    rescue_from Exception, :with => :render_error 
    rescue_from ActiveRecord::RecordNotFound, :with => :render_not_found 
    rescue_from ActionController::UnknownController, :with => :render_not_found 
    rescue_from ActionController::UnknownAction, :with => :render_not_found 
end 

,然后你写你的方法render_errorrender_not_found你想要的方式。在我看来,这似乎是一个非常不合理的解决方案。此外,这很糟糕,因为您必须确切知道可能发生的所有错误。这是一个临时解决方案。

此外,真的没有简单的方法来拯救ActionController::RoutingError这种方式。我看到一个办法是像

get "*not_found", :to => "errors#not_found" 

讲一下你的routes.rb。但是如果您想手动筹集某个地方ActionController::RoutingError怎么办?例如,如果一个非管理员的人试图通过猜测URL去“管理”控制器。在那些情况下,我更喜欢提高404而不是提高某种“未经授权的访问”的错误,因为这实际上会告诉用户他猜到了URL。如果您手动提高它,它会尝试呈现一个500页,我想一个404

那么,有没有办法告诉Rails:“在任何情况下,你通常会呈现一个404.html500.html,使我自定义404和500页“? (当然,我删除从public文件夹中的404.html500.html页。)

回答

1

不幸的是不是我所知道的任何方法可以重写,以提供你想要的。你可以使用周围的过滤器。您的代码会是这个样子:

class ApplicationController < ActionController::Base 
    around_filter :catch_exceptions 

    protected 
    def catch_exceptions 
     yield 
    rescue => exception 
     if exception.is_a?(ActiveRecord::RecordNotFound) 
     render_page_not_found 
     else 
     render_error 
     end 
    end 
end 

你认为合适的那个方法可以处理每个错误。然后你#render_page_not_found#render_error方法就必须是像

render :template => 'errors/404' 

你会那么需要有一个文件在app/views/errors/404.html.[haml|erb]

+0

哇,这真是整齐。这样我就必须知道哪些是“404例外”,这很容易。好的解决方案:)。在你看来,有一个问题是处理未授权访问的最佳方法是什么?提高'ActionController :: RoutingError'实际上并不适合我。 – 2012-02-11 23:38:17

+0

该死的,我不能投票,因为我还没有15点声望点。 – 2012-02-11 23:39:55

+1

我一直使用'head:unauthorized'。这很容易阅读和意图揭示。 – siannopollo 2012-02-12 03:35:32