Raise Error404, don't render and return

Written . Tagged Ruby, Ruby on Rails.

I think it’s fairly common in Rails to define a render_404 method and do

1
render_404 and return

from actions when you want to show a 404 error page (as described here).

A better solution is to raise a custom Error404 exception, then catching that in your ApplicationController and rendering the 404 page.

Not a huge difference, but this means you don’t have to mess with the and return. It also makes it much easier to divide code across methods and classes, since only the current action can return from itself, but any code it calls can raise exceptions that bubble up to the ApplicationController.

I just put

1
class Error404 < StandardError; end

at the top of my app/controllers/application.rb and add

1
rescue_from Error404, :with => :render_404

to the ApplicationController.

The render_404 method is described in the article I mentioned.