Create custom error pages dynamically in ruby on rails 4

The default status code templates are served by a Rack exception application. You can override this to be any Rack compatible app. To override this you need to add following line in your application.rb file.

# config/application.rb
config.exceptions_app = self.routes

Now we need to create ErrorsController:

class ErrorsController < ApplicationController
  def show
    @exception = env['action_dispatch.exception']
    render action: request.path[1..-1]

  def write_to_log_file
    if @exception.present?
      logger.error("Error occured: #{@exception.message}, Status: #{status_code}\n Time: #{}")


  def status_code
    params[:code] || 500

In show method we have added a function to write the exception to log file.

Now create templates for each status code in errors directory. I have created three template for 404.html.erb, 422.html.erb and 500.html.erb

# app/views/errors/404.html.haml
%h1 404 - Not Found

Now create route for this errors:

# config/routes.rb
 %w( 404 422 500 ).each do |code|
    get code, :to => 'errors#show', :code => code

And that’s it for dynamic error page.

Happy coding 🙂


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s