Basic Rails 404错误页面

问题描述 投票:25回答:6

我一直在寻找一个简单的答案,这荒谬的时间很长,而且看起来似乎必须如此明显和简单,因为没有人提供简单易用的傻瓜式教程。

总之,我要做的就是只有一个404.html静态页面,该页面会在引发任何错误时加载。理想情况下,这仅应在生产和分阶段进行。

我觉得这应该是最容易的事情,但是我不知道。

非常感谢您的帮助。

ruby-on-rails routing http-status-code-404
6个回答
20
投票

在您的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,然后就可以了

...或者也许我对Exceptiona谨慎,您应该从RuntimeError中拯救出来。


14
投票

我相信,如果您在生产模式下运行,那么只要没有URL路由,就会提供公共目录中的404.html。


7
投票

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

在Rails 3.1中

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

render:状态=> 500

render:status =>:forbidden

Rails understands both numeric and symbolic status codes.

Fore more information see this page

干杯!


2
投票

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


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.的更多信息


0
投票

这是我的做法。在我的config.action_dispatch.rescue_responses中:

application_controller.rb

然后,在要渲染404的任何控制器中,我都执行以下操作:

def render_404
  render file: 'public/404.html', layout: false, status: :not_found
end
© www.soinside.com 2019 - 2024. All rights reserved.