🖥

Rails – 全てのエラーを rescue_from で吸収する例

に公開

コード例

StandardError を rescue_from することで、全てのエラーを巻き取れそうだ

class ExampleController < ApplicationController
  rescue_from StandardError do
    render status: :ok
  end

  def index
    raise ActiveRecord::RecordInvalid
  end
end

備考

たとえば ActiveRecord::RecordInvalid の祖先を見ると、次のようになっているが、この中の親のどれかを rescue_from しておけばエラーを巻き取れるということのような気がする ( たぶん )

ただしもちろんエラークラス以外を rescue_from してしまうのは宜しくないだろう

ActiveRecord::RecordInvalid.ancestors

# [
#  ActiveRecord::RecordInvalid,
#  ActiveRecord::ActiveRecordError,
#  StandardError,
#  Exception,
#  ActiveSupport::Dependencies::RequireDependency,
#  ActiveSupport::ToJsonWithActiveSupportEncoder,
#  Object,
#  PP::ObjectMixin,
#  ActiveSupport::Tryable,
#  JSON::Ext::Generator::GeneratorMethods::Object,
#  DEBUGGER__::TrapInterceptor,
#  Kernel,
#  BasicObject
# ]

instance method Module#ancestors
クラス、モジュールのスーパークラスとインクルードしているモジュールを優先順位順に配列に格納して返します。

https://docs.ruby-lang.org/ja/latest/method/Module/i/ancestors.html

公開日時

2024-06-26

Discussion