Module: Wajub::Errors

Defined in:
lib/wajub/errors.rb

Class Method Summary collapse

Class Method Details

.from_response(status, body, retry_after: nil) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/wajub/errors.rb', line 41

def from_response(status, body, retry_after: nil)
  message = body['message'] || "Request failed (#{status})"
  code = body['error_code'] || body['code'] || "http_#{status}"
  field_errors = parse_field_errors(body['errors'])

  case status
  when 401 then AuthenticationError.new(message, code: code, http_status: status, errors: field_errors, raw: body)
  when 403 then PermissionError.new(message, code: code, http_status: status, errors: field_errors, raw: body)
  when 404 then NotFoundError.new(message, code: code, http_status: status, errors: field_errors, raw: body)
  when 429 then RateLimitError.new(message, code: code, http_status: status, errors: field_errors, raw: body, retry_after: retry_after)
  when 400, 422 then InvalidRequestError.new(message, code: code, http_status: status, errors: field_errors, raw: body)
  else WajubError.new(message, code: code, http_status: status, errors: field_errors, raw: body)
  end
end

.parse_field_errors(raw) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/wajub/errors.rb', line 56

def parse_field_errors(raw)
  return nil unless raw.is_a?(Hash)

  raw.transform_values do |value|
    value.is_a?(Array) ? value.first.to_s : value.to_s
  end
end