Basic Rails 404 Error Page

2019-01-21 19:49发布

I have been looking for a simple answer to this for a ridiculously long time and it seems like this has to be so plainly obvious and simple because no one has an easy, idiot proof tutorial.

Anyway, all I want to do is to have a single 404.html static page that loads whenever ANY error is thrown. Ideally this should only happen in production and staging.

I feel like this should be the easiest thing to do... but I can't figure it out.

Any help is much appreciated.

5条回答
Deceive 欺骗
2楼-- · 2019-01-21 20:10

in your 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

now set up error_pages/404.html and there you go

...or maybe I'm overcautious with Exception and you should rescue from RuntimeError instead.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-21 20:14

If you run in production mode, 404.html,500.html,422.html files in public directory gets served whenever there respective error occured, pages from above will be shown.

In rails 3.1

We can use like below: Rails 3.1 will automatically generate a response with the correct HTTP status code (in most cases, this is 200 OK). You can use the :status option to change this:

render :status => 500

render :status => :forbidden

Rails understands both numeric and symbolic status codes.

Fore more information see this page

Cheers!

查看更多
干净又极端
4楼-- · 2019-01-21 20:15

Another way of doing this is configuring your config/application.rb with the following:

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

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

So that whenever MyCustomException is raised, Rails treats it as a regular :not_found, rendering public/404.html.

To test this locally, make sure you change config/environments/development.rb to:

config.consider_all_requests_local = false

Read more about config.action_dispatch.rescue_responses.

查看更多
smile是对你的礼貌
5楼-- · 2019-01-21 20:17

I believe that if you run in production mode, then 404.html in the public directory gets served whenever there are no routes for a URL.

查看更多
Fickle 薄情
6楼-- · 2019-01-21 20:25

You won't get a 404 whenever any error is thrown because not all errors result in 404s. That's why you have 404, 422, and 500 pages in your public directory. I guess rails has deemed these to be the most common errors. Like Ben said, 404 will come up when it can't find something, 500 when the application throws an error. Between the two, you can cover a lot of your bases.

查看更多
登录 后发表回答