Yesterday my coworker Eric asked me to build out some dynamic error pages for the upcoming
version of one of our apps. He suggested a certain pattern that we used in a previous application.
Being the adventurous soul that I am, I wanted to make sure his way was the best way. After some
soul google searching, I found out that Eric’s method was considered best practice. It’s
described in some detail on José Valim’s blog post, but I’ll break
it down for you here:
First, we need a controller for our error pages. Start out with something simple, like this:
Now let’s add some routes:
With Rails 3.2, error pages have been extracted to a Rack Middleware. Fortunately for us, so
are the application routes. We can to tell rails to use our routes app for the error pages in
And that’s it! Add some page templates in
app/views/errors/ and you should be good to go.
To test it, we need to turn off the development mode error pages. Set
to false in
You’ll want to set that back to true before committing your code, or else you won’t receive any helpful feedback while developing your application.
All of the above steps were fairly simple, but figuring out how to determine which format to return
is a little complex.
env['REQUEST_PATH'] contains the error path (e.g. “/404”) and no format
information is getting passed to the errors controller, so the standard Rails
respond_to stuff is
not going to work here. We can grab the original request path via
added a few private methods to errors controller to help out. The first two help me figure out what
format the request came as. I want to return a JSON response if the request starts with ‘/api’ or
ends in ‘.json’. The third will render our template in the format we want.
Now we just need to update the actions in our controller:
And we’re done! Make sure you add your json templates to