Exception: Nimbu::Error::ServiceError

Inherits:
NimbuError
  • Object
show all
Includes:
Utils::Json
Defined in:
lib/nimbu-api/errors/service_error.rb

Instance Attribute Summary collapse

Attributes inherited from NimbuError

#response_headers, #response_message

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Utils::Json

#decode

Methods inherited from NimbuError

#backtrace

Methods included from Utils::Descendants

#descendants

Constructor Details

#initialize(response) ⇒ ServiceError

Returns a new instance of ServiceError.



16
17
18
19
20
21
22
# File 'lib/nimbu-api/errors/service_error.rb', line 16

def initialize(response)
  @http_headers = response[:response_headers]
  @status = response[:status]

  message = parse_response(response)
  super(message)
end

Instance Attribute Details

#http_bodyObject (readonly)

Returns the value of attribute http_body.



12
13
14
# File 'lib/nimbu-api/errors/service_error.rb', line 12

def http_body
  @http_body
end

#http_headersObject (readonly)

Returns the value of attribute http_headers.



11
12
13
# File 'lib/nimbu-api/errors/service_error.rb', line 11

def http_headers
  @http_headers
end

#statusObject (readonly)

Returns the value of attribute status.



14
15
16
# File 'lib/nimbu-api/errors/service_error.rb', line 14

def status
  @status
end

Class Method Details

.errorsObject



62
63
64
65
66
# File 'lib/nimbu-api/errors/service_error.rb', line 62

def self.errors
  @errors ||= Hash[
    descendants.map { |klass| [klass.new({}).http_status_code, klass] }
  ]
end

.http_status_code(code) ⇒ Object



58
59
60
# File 'lib/nimbu-api/errors/service_error.rb', line 58

def self.http_status_code(code)
  define_method(:http_status_code) { code }
end

Instance Method Details

#decode_body(body) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/nimbu-api/errors/service_error.rb', line 29

def decode_body(body)
  if body.respond_to?(:to_str) && body.length >= 2
     decode body, :symbolize_keys => true
  else
    body
  end
end

#parse_body(body) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/nimbu-api/errors/service_error.rb', line 37

def parse_body(body)
  body = decode_body(body)

  return '' if body.nil? || body.empty?

  if body[:error]
    body[:error]
  elsif body[:errors]
    error = Array(body[:errors]).first
    if error.kind_of?(Hash)
      error[:message]
    else
      error
    end
  elsif body[:message]
    body[:message]
  else
    ''
  end
end

#parse_response(response) ⇒ Object



24
25
26
27
# File 'lib/nimbu-api/errors/service_error.rb', line 24

def parse_response(response)
  body = parse_body(response[:body])
  "#{response[:method].to_s.upcase} #{response[:url].to_s}: #{response[:status]} #{body}"
end