Class: CongregaPlenum::ResponseHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/adapters/response_handler.rb,
sig/congrega_plenum.rbs

Overview

Centralizes HTTP status validation and JSON parsing.

Instance Method Summary collapse

Instance Method Details

#handle(response, url) ⇒ Hash

Validates an HTTP response code and returns the parsed JSON body.

Parameters:

  • response (Net::HTTPResponse)
  • url (String)
  • (::Net::HTTPResponse)
  • (String)

Returns:

  • (Hash)


11
12
13
14
15
16
17
18
19
20
21
# File 'lib/adapters/response_handler.rb', line 11

def handle(response, url)
  case response.code.to_i
  when 200 then parse_json_response(response, url)
  when 429 then raise RateLimitError, "Rate limit exceeded for #{url}"
  when 404 then raise APIError, "Resource not found: #{url}"
  when 500..599
    raise ServerError, "Server error (#{response.code}) for #{url}: #{response.message}"
  else
    raise APIError, "HTTP Error #{response.code} for #{url}: #{response.message}"
  end
end

#parse_json_response(response, url) ⇒ payload_hash

Parses a JSON response body, raising APIError when invalid.

Parameters:

  • (::Net::HTTPResponse)
  • (String)

Returns:

  • (payload_hash)


26
27
28
29
30
31
32
33
# File 'lib/adapters/response_handler.rb', line 26

def parse_json_response(response, url)
  payload = JSON.parse(response.body)
  return payload if payload.is_a?(Hash)

  raise APIError, "Unexpected JSON payload from #{url}: expected an object"
rescue JSON::ParserError => e
  raise APIError, "Invalid JSON response from #{url}: #{e.message}"
end