Exception: VersSdk::APIError

Inherits:
VersSDKError show all
Defined in:
lib/vers_sdk/errors.rb

Overview

Error returned when the API responds with a non-success status code.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(status: nil, body: nil, message: nil, headers: nil) ⇒ APIError

Returns a new instance of APIError.



14
15
16
17
18
19
# File 'lib/vers_sdk/errors.rb', line 14

def initialize(status: nil, body: nil, message: nil, headers: nil)
  @status = status
  @headers = headers
  @body = body
  super(make_message(status, body, message))
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



12
13
14
# File 'lib/vers_sdk/errors.rb', line 12

def body
  @body
end

#headersObject (readonly)

Returns the value of attribute headers.



12
13
14
# File 'lib/vers_sdk/errors.rb', line 12

def headers
  @headers
end

#statusObject (readonly)

Returns the value of attribute status.



12
13
14
# File 'lib/vers_sdk/errors.rb', line 12

def status
  @status
end

Class Method Details

.generate(status:, body: nil, message: nil, headers: nil) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/vers_sdk/errors.rb', line 32

def self.generate(status:, body: nil, message: nil, headers: nil)
  return APIConnectionError.new(message: message) if status.nil? || headers.nil?

  error_map = {
    400 => BadRequestError,
    401 => AuthenticationError,
    403 => PermissionDeniedError,
    404 => NotFoundError,
    409 => ConflictError,
    422 => UnprocessableEntityError,
    429 => RateLimitError
  }

  error_cls = error_map[status]
  if error_cls
    return error_cls.new(status: status, body: body, message: message, headers: headers)
  end
  if status >= 500
    return InternalServerError.new(status: status, body: body, message: message, headers: headers)
  end

  new(status: status, body: body, message: message, headers: headers)
end

Instance Method Details

#error_messageObject

Extract the human-readable error message from the response body. Looks for an “error” or “message” field in the JSON body, or falls back to the raw message.



24
25
26
27
28
29
30
# File 'lib/vers_sdk/errors.rb', line 24

def error_message
  if body.is_a?(Hash)
    return body["error"] if body["error"].is_a?(String)
    return body["message"] if body["message"].is_a?(String)
  end
  message
end