Rails

Creating Custom Error Pages With Rails

Posted by Weston Ganger on May 09, 2015

If you want to create custom error pages or add layouts and/or assets to your error pages you have a couple of options.


We have a gem that does this, its called gaffe but it does require a fair bit of configuration. So you may just be better off rolling your own as its pretty simple.


Heres how to make your own custom errors setup:

First tell your app to use your routes file to determine how to handle the error pages.


#config/application.rb

config.exceptions_app = self.routes

We will then setup the error routes. For my example im going to setup 404, 422, and 500 error codes


#config/routes.rb

match '/404' => 'errors#error_404'
match '/422' => 'errors#error_422'
match '/500' => 'errors#error_500'

Now create your error controller:


# app/controllers/errors_controller.rb

class ErrorsController < ApplicationController
  def error_404
    respond_to do |format|
      format.html { render status: 404 }
      format.any  { render text: "404 Not Found", status: 404 }
    end
  end

  def error_422
    respond_to do |format|
      format.html { render status: 422 }
      format.any  { render text: "422 Unprocessable Entity", status: 422 }
    end
  end

  def error_500
    render file: "#{Rails.root}/public/500.html", layout: false, status: 500
  end
end

We render the 500 server error with no layout because of the severity of the error the application may not be able to serve any assets.

Now you can add your custom error pages in app/views/errors/


Related External Links:


Posted in Rails and Tagged with rails error 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts