LoginSignup
6
12

More than 5 years have passed since last update.

railsで404や500といったエラーを捕捉(エラーハンドリング)するには?

Last updated at Posted at 2016-09-26

参考: http://ruby-rails.hatenadiary.com/entry/20141111/1415707101

  • 適切なエラー処理の仕方が書いてある
  • 500エラー用Viewもサンプルで書いてある
  • 以下コード一部抜粋
app/controllers/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

  # 他のエラーハンドリングでキャッチできなかった場合に
  # 500 Internal Server Error(システムエラー)を発生させる
  # NOTE: rescue_from は下から評価されるので記載箇所はここが正解
  rescue_from Exception, with: :handle_500 unless Rails.env.development?

  # 例外に合わせたエラーハンドリング
  # 404 Not Found リソースが見つからない。アクセス権がない場合にも使用される
  rescue_from ActionController::RoutingError, with: :handle_404 unless Rails.env.development?
  rescue_from ActiveRecord::RecordNotFound,   with: :handle_404 unless Rails.env.development?
  #rescue_from ActiveRecord::RecordNotUnique, with: :render_409
  #rescue_from UnauthorizedError,             with: :render_401
  #rescue_from IllegalAccessError,            with: :render_403

  # エラーハンドリング処理
  def handle_500(exception = nil)
    logger.info "Rendering 500 with exception: #{exception.message}" if exception

    if request.xhr?
      # Ajaxのための処理
      render json: { error: '500 error' }, status: 500
    else
      render template: 'errors/error_500', status: 500, layout: 'application', content_type: 'text/html'
    end
  end

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

    if request.xhr?
      # Ajaxのための処理
      render json: { error: '404 error' }, status: 404
    else
      render template: 'errors/error_404', status: 404, layout: 'application', content_type: 'text/html'
    end
  end

end

他参考

エラー通知用Webサービス(Rails)

Airbrake

  • エラー通知用のウェブサービス Airbrake の ruby 用プラグイン airbrake
  • airbrakeの良い点
    • exception_notification とは違い同種のエラーであれば複数回発生しても通知は一回だけ送られる
    • web上にエラー内容がまとまってくれる
  • ただ値段に見合っているかはちょっとわからないです。

http://blog.willnet.in/entry/2012/10/21/160240

image

6
12
0

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
6
12