LoginSignup
49
32

More than 5 years have passed since last update.

Railsで404エラーメッセージを出すために

Last updated at Posted at 2016-09-21

railsアプリを作っている最中に404エラーがでないなぁと思い、調べてみると色々と
必要な作業があったので忘れないようにしておきます!

railsには「rescue_from」という便利なメソッドがあったので今回はこれを使います!

rescue_fromを使えばコントローラーで例外をキャッチして、その例外発生時に特定のアクションを実行させることができるそうです!

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

application_controller.rb
class ApplicationController < ActionController::Base

  #ハンドルしきれなかったエラーは500エラー扱い
  if !Rails.env.development?
    rescue_from Exception,                        with: :render_500
    rescue_from ActiveRecord::RecordNotFound,     with: :render_404
    rescue_from ActionController::RoutingError,   with: :render_404
  end

  def routing_error
    raise ActionController::RoutingError.new(params[:path])
  end

  def render_404(e = nil)
    logger.info "Rendering 404 with exception: #{e.message}" if e

    if request.xhr?
      render json: { error: '404 error' }, status: 404
    else
      format = params[:format] == :json ? :json : :html
      render file: Rails.root.join('public/404.html'), status: 404, layout: false, content_type: 'text/html'
    end
  end

  def render_500(e = nil)
    logger.info "Rendering 500 with exception: #{e.message}" if e 

    if request.xhr?
      render json: { error: '500 error' }, status: 500
    else
      format = params[:format] == :json ? :json : :html
      render file: Rails.root.join('public/500.html'), status: 500, layout: false, content_type: 'text/html'
    end
  end

end

public配下にある404.htmlと500.htmlをカスタマイズすれば自分だけのエラーメッセージを出すことが出来ます。

ローカルでエラーメッセージを確認するためにはconfig/environments/development.rbを修正する。

config/environments/development.rb
config.consider_all_requests_local       = false

これでローカルでもエラーメッセージを確認出来ます!

49
32
1

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
49
32