class ExceptionCatcher

ExceptionCatcher makes it easy to execute multiple operations even though any might fail with exception

Attributes

exceptions[R]
mutex[R]
results[R]
tasks[R]

Public Class Methods

new() click to toggle source
# File lib/util/exception_catcher.rb, line 36
def initialize
  @mutex = Mutex.new
  @results = {}
  @exceptions = {}
  @tasks = []
end

Public Instance Methods

catch(task=nil, &block) click to toggle source

Catches exceptions thrown by block @param [Object, nil] task if task is defined, results can be checked per task @param [Proc] block, block which is executed @return [Object, nil] returns block's result or nil if block raised an exception

# File lib/util/exception_catcher.rb, line 47
def catch(task=nil, &block)
  if task.nil?
    task = block
  end
  @mutex.synchronize do
    @tasks << task
  end
  begin
    result = block.call
    @mutex.synchronize do
      @results[task]=result
    end
    result
  rescue Exception => e
    @mutex.synchronize do
      @exceptions[task]=e
    end
    nil
  end
end
check() click to toggle source

Checks if there has been exceptions and raises the original exception if there has been one exception and {MultipleExceptions} if there has been many exceptions

# File lib/util/exception_catcher.rb, line 90
def check
  @mutex.synchronize do
    if @exceptions.size == 1
      e = @exceptions.values.first
      raise e.class, e.message, e.backtrace
    elsif @exceptions.size > 1
      raise MultipleExceptions.new("Caught #{@exceptions.size} exceptions!").catcher(self)
    end
  end
end
exception(task) click to toggle source

@param [Object] task identifies the executed task @return [Object,nil] block's exception or nil if the block did not raise an exception

# File lib/util/exception_catcher.rb, line 78
def exception(task)
  @mutex.synchronize do
    @exceptions[task]
  end
end
exceptions?() click to toggle source

@return [bool] exceptions? returns true if there has been exceptions

# File lib/util/exception_catcher.rb, line 85
def exceptions?
  @exceptions.size > 0
end
result(task) click to toggle source

@param [Object] task identifies the executed task @return [Object,nil] result for the named block or nil if the block ended in exception

# File lib/util/exception_catcher.rb, line 70
def result(task)
  @mutex.synchronize do
    @results[task]
  end
end