Reputation: 195
In my Ruby on Rails application I want to show 404 error page instead of routing error when the given route does not matches or exists in my application. Can anybody help me to make it possible?
Upvotes: 13
Views: 12430
Reputation: 7390
This return 404 page
In ApplicationController
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, with: :route_not_found
rescue_from ActionController::RoutingError, with: :route_not_found
rescue_from ActionController::UnknownFormat, with: :route_not_found
def route_not_found
render file: Rails.public_path.join('404.html'), status: :not_found, layout: false
end
Upvotes: 1
Reputation: 1160
If you cannot easily run production mode locally, set the consider_all_requests_local
to false in your config/environments/development.rb
file.
Upvotes: 21
Reputation: 11967
in ApplicationController
rescue_from ActiveRecord::RecordNotFound, :with => :rescue404
rescue_from ActionController::RoutingError, :with => :rescue404
def rescue404
#your custom method for errors, you can render anything you want there
end
Upvotes: 10
Reputation: 176392
This is already the default behavior in production. In development environment routing errors are displayed to let the developer notice them and fix them.
If you want to try it, start the server in production mode and check it.
$ script/rails s -e production
Upvotes: 14
Reputation: 6519
You could catch exception that is thrown when a route is not found and then render a custom page. Let me know if you need help with the code. There might be many other ways to do this but this definitely works.
Upvotes: 0