1

我试图弄清楚如何使EventMachine::Deferrable回调不引发任何异常。我不是begin ... rescue在每个回调块中都有,而是试图用方法调用以某种方式包装块,以便该方法挽救异常:

require 'eventmachine'

def to_proc
  proc
rescue Exception => e
  puts "e=#{e}"
end

EventMachine::run {
  d = EventMachine::DefaultDeferrable.new
  f =  to_proc {raise 'error'}

  d.callback &f

  EventMachine.next_tick {d.succeed}
}

这当然行不通。我将不胜感激任何帮助。

4

1 回答 1

0

在语句中d.callback &f,调用了 to_proc。无法捕获您试图捕获的异常d.succeed,因为我们已经超出了您的异常处理的上下文。

我实际上不确定您要捕获什么错误。如果您让 EventMachine 做的事情出错,您可以创建一个#errBack来捕获它们。如果您真的想捕获仅在回调中发生的异常,那么您可能应该只在回调中编写异常处理程序(针对您期望的特定异常!)。

但是,如果您真的想捕获所有 proc 中的所有错误,则需要覆盖 Proc 类中的调用:

# Note this code hasn't been tested and is only provided as an example
class Proc
  alias_method :old_call, :call
  def call(*args)
    begin
      old_call(*args)
    rescue Exception => e
      # Handle exception
    end
  end
end

但是我不推荐这种方法

于 2013-03-15T22:32:01.070 回答