LoginSignup
2
0

More than 3 years have passed since last update.

【Rails】カスタム例外の定義とそのハンドリング(カスタム例外を使えと言っている訳ではない)

Last updated at Posted at 2019-08-02

環境

  • Rails 5.2.3

注意

題の通り、カスタム例外の利用を推奨するものではありません。
「業務エラー」と「システムエラー」の違いを認識して、用法・用量を守って利用しましょう。
以下、「業務エラー」と「システムエラー」の違いについて非常に詳しく書かれた参考記事です。
https://qiita.com/jnchito/items/3ef95ea144ed15df3637
https://speakerdeck.com/jnchito/number-rubykansai-2018-01-13

こちらも簡潔で分かりやすいです。
https://waterlow2013.hatenablog.com/entry/2018/06/09/150640

カスタム例外の定義方法

StandardErrorを継承する。

class Payment
  class InvalidRequestError < StandardError; end

  def call
    raise InvalidRequestError 'error message comes here' unless valid?
  end
end

カスタム例外のハンドリング例

呼び出し元は何でもいいですが、ここではとあるAPIと仮定。

module Api
  module V1
    class Payments < Api::BaseController
      rescue_from Payment::InvalidRequestError do |e|
        # e.messageとかを使って何かする。
      end
    end
  end
end
2
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
2
0