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!