Module: FiniteMachine::Catchable

Included in:
StateMachine
Defined in:
lib/finite_machine/catchable.rb

Overview

A mixin to allow for specifying error handlers

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Extends object with error handling methods



9
10
11
12
13
# File 'lib/finite_machine/catchable.rb', line 9

def self.included(base)
  base.module_eval do
    attr_threadsafe :error_handlers, default: []
  end
end

Instance Method Details

#catch_error(exception) ⇒ Boolean

Catches error and finds a handler

Parameters:

  • exception (Exception)

Returns:

  • (Boolean)

    true if handler is found, nil otherwise



50
51
52
53
54
55
# File 'lib/finite_machine/catchable.rb', line 50

def catch_error(exception)
  if handler = handler_for_error(exception)
    handler.arity.zero? ? handler.call : handler.call(exception)
    true
  end
end

#handle(*exceptions, &block) ⇒ Object

Rescue exception raised in state machine

Examples:

handle TransitionError, with: :pretty_errors
handle TransitionError do |exception|
  logger.info exception.message
  raise exception
end

Parameters:

  • exceptions (Array[Exception])


29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/finite_machine/catchable.rb', line 29

def handle(*exceptions, &block)
  options = exceptions.last.is_a?(Hash) ? exceptions.pop : {}

  unless options.key?(:with)
    if block_given?
      options[:with] = block
    else
      raise ArgumentError, "Need to provide error handler."
    end
  end
  evaluate_exceptions(exceptions, options)
end