0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

Posted at

コード例

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
クラス、モジュールのスーパークラスとインクルードしているモジュールを優先順位順に配列に格納して返します。

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?