LoginSignup
282
274

More than 5 years have passed since last update.

Railsの404,500エラーページをカスタマイズ

Posted at

Railsはエラーページをもともと用意してくれていて本番で動かすと
そこに飛ばしてくれるので、まぁいいっちゃいいのですが、
簡単に設定できるのでやってしまえばいいかと。
(レイアウトとかそのまま使えてサイト内ページっぽくなるし)


■環境
Rails 4.0.3
Ruby 2.1.1


とりあえずローカルで見たいのでWEBric(rails s)を本番設定で起動して確認します。
(developmentのままだといつもの赤いページが表示されます)

まず、ActionController::RoutingErrorを拾うためにroutesに設定が必要です。

# config/routes.rb

# どこにも当てはまらなかったものを取得するので最終行に書いて下さい。
get '*path', to: 'application#render_404'

次にapplicationコントローラに設定を書きます。


class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  rescue_from ActiveRecord::RecordNotFound, with: :render_404
  rescue_from ActionController::RoutingError, with: :render_404
  rescue_from Exception, with: :render_500

  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

  def render_500(exception = nil)
    if exception
      logger.info "Rendering 500 with exception: #{exception.message}"
    end
    render template: "errors/error_500", status: 500, layout: 'application'
  end
end

あとはviews以下にerrorsディレクトリを作ってそれぞれ
error_400.slim(haml)とerror_500.slimを置いて
好きなようにデザインして下さい。

applicationコントローラじゃなくてerorrsコントローラとかにしたいとかは
適当にパスを書き換えればできます。

282
274
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
282
274