Module: Insights::API::Common::ApplicationControllerMixins::ExceptionHandling

Defined in:
lib/insights/api/common/application_controller_mixins/exception_handling.rb

Constant Summary collapse

DEFAULT_ERROR_CODE =
400

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(other) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/insights/api/common/application_controller_mixins/exception_handling.rb', line 8

def self.included(other)
  other.rescue_from(StandardError, RuntimeError) do |exception|
    logger.error("#{exception.class.name}: #{exception.message}\n#{exception.backtrace.join("\n")}")
    errors = Insights::API::Common::ErrorDocument.new.tap do |error_document|
      exception_list_from(exception).each do |exc|
        if api_client_exception?(exc)
          api_client_errors(exc, error_document)
        else
          error_document.add(error_code_from_class(exc).to_s, "#{exc.class}: #{exc.message}")
        end
      end
    end

    render :json => errors.to_h, :status => error_code_from_class(exception)
  end
end

Instance Method Details

#api_client_errors(exc, error_document) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/insights/api/common/application_controller_mixins/exception_handling.rb', line 47

def api_client_errors(exc, error_document)
  body = JSON.parse(exc.response_body)
  if body.is_a?(Hash) && body.key?('errors') && body['errors'].is_a?(Array)
    body['errors'].each do |error|
      next unless error.key?('status') && error.key?('detail')

      error_document.add(error['status'], error['detail'])
    end
  else
    error_document.add(exc.code.to_s, exc.message )
  end
end

#api_client_exception?(exc) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
45
# File 'lib/insights/api/common/application_controller_mixins/exception_handling.rb', line 42

def api_client_exception?(exc)
  exc.respond_to?(:code) && exc.respond_to?(:response_body) && exc.respond_to?(:response_headers) &&
    !exc.response_body.nil?
end

#error_code_from_class(exception) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/insights/api/common/application_controller_mixins/exception_handling.rb', line 34

def error_code_from_class(exception)
  if ActionDispatch::ExceptionWrapper.rescue_responses.key?(exception.class.to_s)
    Rack::Utils.status_code(ActionDispatch::ExceptionWrapper.rescue_responses[exception.class.to_s])
  else
    DEFAULT_ERROR_CODE
  end
end

#exception_list_from(exception) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/insights/api/common/application_controller_mixins/exception_handling.rb', line 25

def exception_list_from(exception)
  [].tap do |arr|
    until exception.nil?
      arr << exception
      exception = exception.cause
    end
  end
end