Module: Payhub::Errors

Defined in:
lib/payhub/errors.rb

Defined Under Namespace

Classes: APIError, AuthenticationError, ConnectionError, DecodeError, Error, GatewayError, IdempotencyConflictError, NotFoundError, PermissionError, RateLimitedError, ServerError, TimeoutError, TransportError, ValidationError

Class Method Summary collapse

Class Method Details

.from_envelope(envelope, http_status, retry_after: nil) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/payhub/errors.rb', line 49

def from_envelope(envelope, http_status, retry_after: nil)
  err = (envelope.is_a?(Hash) && envelope["error"].is_a?(Hash)) ? envelope["error"] : {}
  code = err["code"] || "hub.unknown"
  message = err["message"] || "HTTP #{http_status}"
  details = err["details"] || {}
  request_id = err["request_id"]
  common = {code: code, http_status: http_status, details: details, request_id: request_id}

  case http_status
  when 401 then AuthenticationError.new(message, **common)
  when 403 then PermissionError.new(message, **common)
  when 404 then NotFoundError.new(message, **common)
  when 409 then IdempotencyConflictError.new(message, **common)
  when 422 then ValidationError.new(message, **common)
  when 429 then RateLimitedError.new(message, retry_after: retry_after, **common)
  else
    if (500..599).cover?(http_status)
      code.start_with?("gateway.") ? GatewayError.new(message, **common) : ServerError.new(message, **common)
    else
      APIError.new(message, **common)
    end
  end
end