Create a 404 error page for RAILS

Source: Internet
Author: User

I recently launched www.gkvision.com in a project, but I found that I have not specified a 404 error for the application, and the entered error address is actually a route error, this instantly made my website very bad, so I quickly added the Error 404 page for this project.

Scenario 1

I added the error method to a controller of the project and put the 404 page in views. Now we add a condition in route when none of the conditions can be matched, as shown below:

match "*a" => "home#error"

In this way, if none of the above conditions match, the sentence will be executed and jump to my 404 interface.

Case 2

In this way, the routing error occurs, but there are other situations. For example, if we display a photo album, the general path is

/Show? Album_id = 3

When processing in the background, sometimes the id cannot be found. If you are using the find method, an ActiveRecord: RecordNotFound error will be thrown. If you are using the find_by_id or other syntax, returns only an empty array). You can add this exception in application_controller.rb as follows:

rescue_from ActiveRecord::RecordNotFound, :with => :show_error

If you want to catch other exceptions, you can write them here.


rescue_from ActionView::MissingTemplate,:with => :show_errorrescue_from ActionView::Template::Error,:with => :show_errorrescue_from ActionController::RoutingError, :with => :show_errorrescue_from ActionController::UnknownController, :with => :show_error

Case 3

However, if you use methods such as find_by_id in the program, it will only find errors when you use this instance, so we can do this.

begin @album =  @theme.albums.first  rescue    redirect_to error_path  end

In this way, when any error occurs when this instance is used, we redirect it to 404.

This article is from the blog "don't be afraid of mistakes, don't worry". For more information, please contact the author!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.