183
155

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsで404/500エラーの処理

Last updated at Posted at 2014-05-05

Railsで404/500エラーの処理をする

application_controllerを編集

app/controllers/application_controller.rb
# 例外処理
rescue_from ActiveRecord::RecordNotFound, with: :render_404
rescue_from ActionController::RoutingError, with: :render_404
rescue_from Exception, with: :render_500

def render_404
  render template: 'errors/error_404', status: 404, layout: 'application', content_type: 'text/html'
end

def render_500
  render template: 'errors/error_500', status: 500, layout: 'application', content_type: 'text/html'
end

エラーページのviewファイルを作成

動的にページを表示する場合

app/views/errors/error_404.html.erbapp/views/errors/error_500.html.erbを作成する。
(静的ページを表示する場合は、public配下に作成)

ルートファイルを編集

config/routes.rbの一番下に以下を書く。

config/routes.rb
get '*path', controller: 'application', action: 'render_404'

ローカル環境でエラー処理の動作確認をする場合

development環境でエラーページの動作を確認する場合は、config/environments/development.rbを以下のようにfalseにする。

config/environments/development.rb
config.consider_all_requests_local       = false
183
155
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
183
155

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?