Claasloader

My IT blog

Error Pages in Rails: You're Still Doing It Wrong

Error pages are important. Well, so important, there are even books written about it.

For your shiny new Rails app, you most often want to customize the error pages (404 and 500). Rails’ standard pages are not appropriate for most use cases (how could they).

Usually, you want to include your page logo image, some common page headers, and at least one link back into your application. The layout of the error page should be at least similar to the rest of the application. Now there’s a problem: By default, error pages are static html files. This makes totally sense, since in case of serious server problems, your Rails app might not be able to create the error page dynamically anymore. On the other hand, you cannot reference your standard CSS resources in a static html file since you don’t know the Asset Pipeline ids in advance.

When you google this problem, people recommend pretty complicated strategies like:

Instead, I recommend a much simpler solution:

  • Add controller actions for 404 and 500
  • Use ERB or Haml to style your error pages nicely
  • Right after deployment, call your 404 and 500 actions and save them as static HTML files

It would require only a few lines in Capistrano (thanks to my colleague Ali for figuring out the details):

./lib/capistrano/tasks/error_pages.rake
1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace :error_pages do
  desc 'Generate static error pages and save in public folder'
  task :create do
    on roles(:web) do |host|
      public_500_html = File.join(release_path, "public/500.html")
      execute :curl, '-s', "https://www.example.com/500_page", "> #{public_500_html}"

      public_404_html = File.join(release_path, "public/404.html")
      execute :curl, '-s', "https://www.example.com/404_page", "> #{public_404_html}"
    end
  end
end

after 'deploy:published', 'error_pages:create'