Class: DaemonKit::Safety

Inherits:
Object show all
Defined in:
lib/daemon_kit/safety.rb

Overview

Provides a wrapper for running code inside a ‘safety net’ Any exceptions raised inside a safety net is handled and reported via loggers, email or Hoptoad.

The safety net can be configured via DaemonKit.config.safety, which holds the only instance of the safety net.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#error_handlersObject (readonly)

Returns the value of attribute error_handlers.



16
17
18
# File 'lib/daemon_kit/safety.rb', line 16

def error_handlers
  @error_handlers
end

#handlerObject

Returns the value of attribute handler.



12
13
14
# File 'lib/daemon_kit/safety.rb', line 12

def handler
  @handler
end

Class Method Details

.instanceObject



23
24
25
# File 'lib/daemon_kit/safety.rb', line 23

def instance
  @instance ||= new
end

.register_error_handler(klass) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/daemon_kit/safety.rb', line 33

def register_error_handler( klass )
  name = klass.to_s.split('::').last.downcase

  DaemonKit.logger.debug( "Registering error handler '#{name}' (#{klass})" ) if DaemonKit.logger

  instance.instance_eval( <<-EOF, __FILE__, __LINE__ )
  def #{name}
    @#{name} ||= #{klass}.instance
  end
  EOF
end

.run(&block) ⇒ Object

Run the provided block inside a safety net.



29
30
31
# File 'lib/daemon_kit/safety.rb', line 29

def run(&block)
  self.instance.run(&block)
end

Instance Method Details

#get_handlerObject



59
60
61
62
63
64
65
66
# File 'lib/daemon_kit/safety.rb', line 59

def get_handler
  if @handler && self.respond_to?( @handler )
    h = send( @handler )
    return h if h.class.ancestors.include?( DaemonKit::ErrorHandlers::Base )
  end

  return nil
end

#run(&block) ⇒ Object

Run the provided block inside a safety net.



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/daemon_kit/safety.rb', line 47

def run(&block)
  begin
    block.call
  rescue => e
    # Log
    DaemonKit.logger.fatal "Safety net caught exception: #{e.message}"
    DaemonKit.logger.fatal "Backtrace: #{e.backtrace.join("\n    ")}"

    get_handler.handle_exception( e ) if get_handler
  end
end