0

外部の Ruby gem を利用するプログラムを作成しました。私はこれでさまざまなアクションを実行しているので、メソッドを呼び出すたびに例外を実装するのではなく、全面的に例外をレスキューして処理できるようにしたいと考えています。

これを行う最善の方法は何ですか?
単純に外部 gem を呼び出し、例外をレスキューする独自のメソッドを作成する必要がありますか? または、「このタイプの例外がプログラムのどこかで発生するたびに、この方法で処理する」のような別の方法はありますか?

外部の gem コードを記述した場合、そのようなエラー処理を追加できることはわかっていますが、それは実現不可能です。

4

1 に答える 1

1

これに対する基本的な答えは、おそらく作業中のクラスをラップすることです。Ruby には method_missing とかなり動的なクラス環境があるため、これを行うための柔軟性が非常に高くなります。以下に例を示します (致命的な欠陥がある場合とそうでない場合がありますが、原則を示しています。

# A Foo class that throws a nasty exception somewhere.
class Foo
  class SpecialException < Exception; end

  def bar
    raise SpecialException.new("Barf!")
  end
end

# This will rescue all exceptions and optionally call a callback instead
# of raising.
class RescueAllTheThings
  def initialize(instance, callback=nil)
    @instance = instance
    @callback = callback
  end

  def method_missing(method, *args, &block)
    if @instance.respond_to? method
      begin
        @instance.send(method, *args, &block)
      rescue Exception => e
        @callback.call(e) if @callback
      end
    else
      super
    end
  end
end

# A normal non-wrapped Foo. Exceptions will propagate.
raw_foo = Foo.new

# We'll wrap it here with a rescue so that we don't exit when it raises.
begin
  raw_foo.bar
rescue Foo::SpecialException
  puts "Uncaught exception here! I would've exited without this local rescue!"
end

# Wrap the raw_foo instance with RescueAllTheThings, which will pass through
# all method calls, but will rescue all exceptions and optionally call the
# callback instead. Using lambda{} is a fancy way to create a temporary class
# with a #call method that runs the block of code passed. This code is executed
# in the context *here*, so local variables etc. are usable from wherever the
# lambda is placed.
safe_foo = RescueAllTheThings.new(raw_foo, lambda { |e| puts "Caught an exception: #{e.class}: #{e.message}" })

# No need to rescue anything, it's all handled!
safe_foo.bar

puts "Look ma, I didn't exit!"

上記の RescueAllTheThings クラスなどの非常に一般的なバージョンのラッパー クラスを使用することが理にかなっているのか、ラップしようとしているものにより具体的なものを使用することが理にかなっているのかは、コンテキストと探している特定の問題に大きく依存します。解決する。

于 2013-05-09T04:52:21.757 に答える