プログラミングガール

Developing a better me

Rails|エラーページのカスタマイズ

なにがしたい

エラーページをいい感じにカスタマイズしたい。

HOW TO

1. view配下にerrorsディレクトリを切り、「error_404.html.erb」と「500.html.erb」を作成 2. application_controller.rbに下記を記述

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  rescue_from ActionController::RoutingError, with: :render_404
  rescue_from Exception, with: :render_500

  # 404ページをレンダリング
  def render_404(exception = nil)
    if exception
      logger.info "Rendering 404 with exception: #{exception.message}"
    end
    render template: "errors/error_404", status: 404, layout: 'application'
  end

  # 500ページをレンダリング
  def render_500(exception = nil)
    if exception
      logger.info "Rendering 500 with exception: #{exception.message}"
    end
    render template: "errors/error_50x", status: 500, layout: 'application'
  end
end

3. route.rbの最後に下記を記述 その上に書かれているパス以外のリクエストが来たら、404ページに遷移させます。

 get '*path', to: 'application#render_404'