Class: Direct::ExceptionHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/direct/exception_handler.rb

Overview

This class monitors exception types with related blocks.

Instance Method Summary collapse

Constructor Details

#initializeExceptionHandler

Returns a new instance of ExceptionHandler.



4
5
6
# File 'lib/direct/exception_handler.rb', line 4

def initialize
  @handlers = {}
end

Instance Method Details

#call(deferred, exception, object) ⇒ Object

This will find the first handler given to ‘monitor` which matches the provided exception’s class and will execute it with the deferred object, the exception object, and any given object to the deferred object.



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/direct/exception_handler.rb', line 24

def call(deferred, exception, object)
  if_none = proc { raise "No handler for this exception: #{exception.class}!" }
  result = @handlers.find { |key, val| key.include?(exception.class) }
  if result.nil?
    result = @handlers.find(if_none) do |key, val|
      key.find { |klass| exception.class < klass }
    end
  end

  result.last.call(deferred, exception, object)
end

#classesObject

All classes, including StandardError, for which this object maintains a block to execute.



10
11
12
# File 'lib/direct/exception_handler.rb', line 10

def classes
  [StandardError, @handlers.keys.flatten].flatten
end

#monitor(*classes, &block) ⇒ Object

Pass a single or multiple exception classes and the block to be used to handle them.



16
17
18
# File 'lib/direct/exception_handler.rb', line 16

def monitor(*classes, &block)
  @handlers[classes.flatten] = block
end