2009-09-19 64 views
25

我一直在寻找一个简单的答案,这个很可笑的时间很长,看起来像这样必须是如此明显而简单,因为没有人有一个简单,傻瓜证明教程。基本导轨404错误页面

无论如何,我想要做的只是一个单一的404.html静态页面,加载任何错误时抛出。理想情况下,这应该只在生产和舞台上发生。

我觉得这应该是最简单的事情......但我无法弄清楚。

任何帮助,非常感谢。

+0

问得好@chishomer,我给出最好的答案。检查一下。 http://stackoverflow.com/questions/1447627/basic-rails-404-error-page/8987083#answer-8987083 –

回答

19

ApplicationController

unless ActionController::Base.consider_all_requests_local 
    rescue_from Exception, :with => :render_404 
end 

private 

    def render_404 
    render :template => 'error_pages/404', :layout => false, :status => :not_found 
    end 

现在设立error_pages/404.html和你去那里

...也许我缩手缩脚与异常,你应该从RuntimeError抢救代替。

+1

感谢您的答案,我也想补充说,有一个深入的写作,我发现这个话题 http://www.perfectline.co.uk/blog/custom-dynamic-error-pages-in-ruby-on-rails – Schneems

+0

它似乎不适用于Rails 3 – hoyhoy

+2

它应该工作,虽然文档说你应该使用'Rails.application.config.consider_all_requests_local'而不是'ActionController :: Base.consider_all_requests_local'。 –

14

我相信,如果您在生产模式下运行,那么每当没有URL的路由时,公共目录中的404.html将被获取。

2

每当发生任何错误时都不会得到404,因为并非所有错误都会导致404错误。这就是为什么你的公共目录中有404,422和500页。我想铁轨已经认为这是最常见的错误。像Ben说的那样,404会在找不到东西时出现,500当应用程序抛出错误时。在这两者之间,你可以覆盖很多你的基地。

7

如果您在生产模式下运行,每当发生相应错误时,公共目录中的404.html,500.html,422.html文件都会得到处理,则会显示上面的页面。

在Rails 3.1

我们可以使用如下: 的Rails 3.1将自动生成正确的HTTP状态码的响应(在大多数情况下,这是200 OK)。您可以使用:状态选项更改此:

渲染:状态=> 500

渲染:状态=>:禁止

Rails understands both numeric and symbolic status codes.

Fore more information see this page

干杯!

0

这样做的另一种方式是用下面的配置您的config/application.rb

module YourApp 
    class Application < Rails::Application 
    # ... 

    config.action_dispatch.rescue_responses.merge!(
     'MyCustomException' => :not_found 
    ) 
    end 
end 

所以,每当MyCustomException升高,Rails的把它当作一个普通:not_found,渲染public/404.html

要在本地测试,确保你改变config/environments/development.rb到:

config.consider_all_requests_local = false 

了解更多关于config.action_dispatch.rescue_responses.