Reputation: 4920
I have been looking for a simple answer to this for a ridiculously long time and it seems like this has to be so plainly obvious and simple because no one has an easy, idiot proof tutorial.
Anyway, all I want to do is to have a single 404.html static page that loads whenever ANY error is thrown. Ideally this should only happen in production and staging.
I feel like this should be the easiest thing to do... but I can't figure it out.
Any help is much appreciated.
Upvotes: 26
Views: 25287
Reputation: 45174
Here's how I do it. In my application_controller.rb
:
def render_404
render file: 'public/404.html', layout: false, status: :not_found
end
Then, in any controller where I want to render a 404, I do something like this:
@appointment = Appointment.find_by(id: params[:appointment_id]) || render_404
Upvotes: 3
Reputation: 1111
Another way of doing this is configuring your config/application.rb
with the following:
module YourApp
class Application < Rails::Application
# ...
config.action_dispatch.rescue_responses.merge!(
'MyCustomException' => :not_found
)
end
end
So that whenever MyCustomException
is raised, Rails treats it as a regular :not_found
, rendering public/404.html
.
To test this locally, make sure you change config/environments/development.rb
to:
config.consider_all_requests_local = false
Read more about config.action_dispatch.rescue_responses
.
Upvotes: 0
Reputation: 32070
If you run in production mode, 404.html,500.html,422.html files in public directory gets served whenever there respective error occured, pages from above will be shown.
In rails 3.1
We can use like below: Rails 3.1 will automatically generate a response with the correct HTTP status code (in most cases, this is 200 OK). You can use the :status option to change this:
render :status => 500
render :status => :forbidden
Rails understands both numeric and symbolic status codes.
Fore more information see this page
Cheers!
Upvotes: 7
Reputation: 14189
in your ApplicationController
unless ActionController::Base.consider_all_requests_local
rescue_from Exception, :with => :render_404
end
private
def render_404
render :template => 'error_pages/404', :layout => false, :status => :not_found
end
now set up error_pages/404.html
and there you go
...or maybe I'm overcautious with Exception and you should rescue from RuntimeError instead.
Upvotes: 20
Reputation: 25794
You won't get a 404 whenever any error is thrown because not all errors result in 404s. That's why you have 404, 422, and 500 pages in your public directory. I guess rails has deemed these to be the most common errors. Like Ben said, 404 will come up when it can't find something, 500 when the application throws an error. Between the two, you can cover a lot of your bases.
Upvotes: 2
Reputation: 143194
I believe that if you run in production mode, then 404.html in the public directory gets served whenever there are no routes for a URL.
Upvotes: 14