Show 404 instead of 500 in Rails

In my rails app, I defined routes so that users can access entries like http://mydomain.com/qwe2

But if they enter the wrong "qwe2", they get 500 pages. I think 404 would be more appropriate.

How can I change the error page displayed? Thanks

+4
source share
2 answers

The only reason you get the 500 code is because your application throws an exception. This could be due to a missing route where you have nothing specific that matches this, or due to a failure of your controller or view.

In a production environment, you may want to catch all the errors generated by your application and, if necessary, show the best error screen or the "Not Found" page.

For example, the catch-all catch general exception trap can be defined as:

class ApplicationController < ActionController::Base if (Rails.env.production?) rescue_from Object, :with => :uncaught_exception_rescue end protected def uncaught_exception_rescue(exception) render(:partial => 'errors/not_found', :status => :not_found) end end 

Returning a 404 error is easy if you can tell when you want to do this:

 render(:partial => 'errors/not_found', :status => :not_found) 

Make sure you have some default route, or you will get these errors all the time. This is usually done by adding a catch-all route at the very end of your routes. Rb:

 map.default '/*path', :controller => 'default', :action => 'show' 

Then you can do whatever you want with this query.

+6
source

Create a route for everyone at the bottom of config/routes.rb :

 map.connect '*path', :controller => 'unknown_route' 

Then in app/controllers/unknown_route_controller you can do:

 class UnknownRouteController < ApplicationController def index render :file => "#{Rails.root}/public/404.html", :layout => false, :status => 404 end end 

This will make your page 404 for any unknown routes.

+6
source

Source: https://habr.com/ru/post/1305665/


All Articles