Reputation: 789
I know how to handle error which RecordNotFound
But how can I handle Routing Error (No route matches [GET])?
PS in this topic I don't find an answer - Rails - how to handle routes that don't exist ("No route matches [GET]")?
Upvotes: 2
Views: 1140
Reputation: 1462
Another way to handle routing (and all others) is to add the following in your ApplicationController:
unless Rails.application.config.consider_all_requests_local
rescue_from Exception do |e|
render_500 e
end
rescue_from ActionController::RoutingError, with: :render_404
rescue_from ActionController::UnknownController, with: :render_404
rescue_from ActionController::UnknownAction, with: :render_404
rescue_from ActiveRecord::RecordNotFound, with: :render_404
end
Then make sure to define render_500
and render_404
so that they actually render something. In my app, I've done:
def render_404(exception)
@not_found_path = exception.message
respond_to do |format|
format.html { render template: 'errors/error_404', layout: 'layouts/application', status: 404 }
format.all { render nothing: true, status: 404 }
end
end
And then created a template in errors/error_404
. That way it handles all routing errors and still uses my application layout.
You can use @not_found_path to show the error to the user.
Upvotes: 6
Reputation: 3846
After every other route in you config/routes.rb
, add this line :
match '*url' => 'errors#routing'
Then create a controller called ErrorsController
and add a routing
action where you can use params[:url]
to know which URL has caused the 404.
By the way, it is a good way to see if your website has dead links.
Hope it helps !
Upvotes: 3