LoginSignup
1
0

More than 1 year has passed since last update.

rescue_fromを活用して、不足の事態に備えましょう!

Posted at

例外とは

例外(Exception)とは、変則的な事態のことで、例外が発生すると通常の流れから外れて特別な処理に移行します。Ruby言語には、例外を表現するためのExceptionクラスが用意されています。
普段目にするエラーのほとんどは、以下のような継承をしています。

Exception
↓
StandardError
↓
ActiveRecord::ActiveRecordError
↓
ActiveRecord::RecordNotFoundなど、普段目にするエラー

rescue_fromとは

アクション内で発生した例外の処理方法を指定するクラスメソッドのことです。
rescue_from エラー, with: :メソッド名の形で指定する。
※通常、application_controller.rbに記載する。

記載例

app/controllers/application_controller.rb
class ApplicationController<ActionController::Base

  class Forbidden < ActionController::ActionControllerError; end
  class IpAddressRejected < ActionController::ActionControllerError; end


  # StandardError発生時、rescue_500メソッドを実行する
  rescue_from StandardError, with: :rescue_500

  # ForbiddenもしくはIpAddressRejected発生時、rescue_403メソッドを実行する
  rescue_from Forbidden, with: :rescue_403
  rescue_from IpAddressRejected, with: :rescue_403

  # ActiveRecord::RecordNotFound発生時、rescue_404メソッドを実行する
  rescue_from ActiveRecord::RecordNotFound, with: :rescue_404

  private

  def rescue_403(e)
    @exception = e
    render 'errors/forbidden', status: 403
  end

  def rescue_404(e)
    render 'errors/not_found', status: 404
  end


  def rescue_500(e)
    render 'errors/internal_server_error', status: 500
  end
end

注意点

  • 引数のeにははExceptionオブジェクトが渡される。
  • 親子関係(あるいは先祖・子孫の関係)にある例外をrescue_fromに指定する場合、親(先祖)の方を先に指定する。
  • application_controller.rb内が複雑になってきたら、モジュールとして抽出する。
1
0
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
1
0