Creating Custom Error Pages With Rails

Posted By Weston Ganger

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.

# 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:

Article Topic:Software Development - Ruby / Rails

Date:May 09, 2015