Class: Exceptron::Dispatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/exceptron/dispatcher.rb

Constant Summary collapse

FAILSAFE_RESPONSE =
[500, {'Content-Type' => 'text/html'},
      ["<html><head><title>500 Internal Server Error</title></head>" +
"<body><h1>500 Internal Server Error</h1>If you are the administrator of " +
"this website, then please read this web application's log file and/or the " +
"web server's log file to find out what went wrong.</body></html>"]]

Instance Method Summary collapse

Constructor Details

#initialize(consider_all_requests_local) ⇒ Dispatcher

Returns a new instance of Dispatcher.



9
10
11
12
# File 'lib/exceptron/dispatcher.rb', line 9

def initialize(consider_all_requests_local)
  @consider_all_requests_local = consider_all_requests_local
  @exception_actions_cache = {}
end

Instance Method Details

#dispatch(env, exception) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/exceptron/dispatcher.rb', line 14

def dispatch(env, exception)
  log_error(exception.wrapped_exception)

  local = @consider_all_requests_local || ActionDispatch::Request.new(env).local?
  controller = exception_controller(local)
  action = exception_action(local, controller, exception)

  if action
    controller.action(action).call(env)
  else
    FAILSAFE_RESPONSE
  end
rescue Exception => failsafe_error
  $stderr.puts "Error during failsafe response: #{failsafe_error}"
  $stderr.puts failsafe_error.backtrace.join("\n")
  FAILSAFE_RESPONSE
end

#exception_action(local, controller_klass, exception) ⇒ Object



36
37
38
39
40
41
# File 'lib/exceptron/dispatcher.rb', line 36

def exception_action(local, controller_klass, exception)
  controller = controller_klass.new
  @exception_actions_cache[controller_klass] ||= {}
  @exception_actions_cache[controller_klass][exception.original_exception.class] ||=
    exception.actions.find { |action| controller.available_action?(action) }
end

#exception_controller(local) ⇒ Object



32
33
34
# File 'lib/exceptron/dispatcher.rb', line 32

def exception_controller(local)
  local ? Exceptron.local_controller : Exceptron.controller
end

#log_error(exception) ⇒ Object



43
44
45
46
47
48
49
50
51
52
# File 'lib/exceptron/dispatcher.rb', line 43

def log_error(exception)
  return unless logger

  ActiveSupport::Deprecation.silence do
    message = "\n#{exception.class} (#{exception.message}):\n"
    message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
    message << exception.backtrace.join("\n  ")
    logger.fatal("#{message}\n\n")
  end
end

#loggerObject



54
55
56
# File 'lib/exceptron/dispatcher.rb', line 54

def logger
  defined?(Rails.logger) ? Rails.logger : Logger.new($stderr)
end