Exception: Pingram::ApiError

Inherits:
StandardError
  • Object
show all
Defined in:
lib/pingram/api_error.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(arg = nil) ⇒ ApiError

Usage examples:

ApiError.new
ApiError.new("message")
ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
ApiError.new(:code => 404, :message => "Not Found")


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/pingram/api_error.rb', line 52

def initialize(arg = nil)
  if arg.is_a? Hash
    if arg.key?(:message) || arg.key?('message')
      super(arg[:message] || arg['message'])
    else
      super arg
    end

    arg.each do |k, v|
      instance_variable_set "@#{k}", v
    end
  else
    super arg
    @message = arg
  end
end

Instance Attribute Details

#codeObject (readonly)

Returns the value of attribute code.



16
17
18
# File 'lib/pingram/api_error.rb', line 16

def code
  @code
end

#response_bodyObject (readonly)

Returns the value of attribute response_body.



16
17
18
# File 'lib/pingram/api_error.rb', line 16

def response_body
  @response_body
end

#response_headersObject (readonly)

Returns the value of attribute response_headers.



16
17
18
# File 'lib/pingram/api_error.rb', line 16

def response_headers
  @response_headers
end

Class Method Details

.extract_api_error_detail(payload) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/pingram/api_error.rb', line 18

def self.extract_api_error_detail(payload)
  return nil if payload.nil?

  raw = payload.is_a?(String) ? payload : payload.to_s
  return nil if raw.strip.empty?

  begin
    h = JSON.parse(raw)
  rescue JSON::ParserError
    return nil
  end
  return nil unless h.is_a?(Hash)

  err = h['error'] || h[:error]
  if err.is_a?(Hash)
    m = err['message'] || err[:message]
    return m.to_s if m && !m.to_s.strip.empty?
  end
  m = h['message'] || h[:message]
  return m.to_s if m && !m.to_s.strip.empty?
  msgs = h['messages'] || h[:messages]
  if msgs.is_a?(Array) && !msgs.empty?
    first = msgs[0]
    return first.to_s if first && !first.to_s.strip.empty?
  end

  nil
end

Instance Method Details

#messageObject



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/pingram/api_error.rb', line 74

def message
  detail = self.class.extract_api_error_detail(@response_body)
  msg = nil
  msg = detail if detail && !detail.strip.empty?

  if msg.nil?
    if @message.nil?
      msg = 'Error message: the server returns an error'
    else
      msg = @message.to_s
    end
  end

  msg += "\nHTTP status code: #{code}" if code
  msg += "\nResponse headers: #{response_headers}" if response_headers
  msg += "\nResponse body: #{response_body}" if response_body

  msg
end

#to_sObject

Override to_s to display a friendly error message



70
71
72
# File 'lib/pingram/api_error.rb', line 70

def to_s
  message
end