Module: Castle::Core::ProcessResponse
- Defined in:
- lib/castle/core/process_response.rb
Overview
parses api response
Constant Summary collapse
- RESPONSE_ERRORS =
{ 400 => Castle::BadRequestError, 401 => Castle::UnauthorizedError, 403 => Castle::ForbiddenError, 404 => Castle::NotFoundError, 419 => Castle::UserUnauthorizedError, 429 => Castle::RateLimitError }.freeze
- INVALID_REQUEST_TOKEN =
'invalid_request_token'
Class Method Summary collapse
Class Method Details
.call(response, config = nil) ⇒ Hash
22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/castle/core/process_response.rb', line 22 def call(response, config = nil) verify!(response) Castle::Logger.call('response:', response.body.to_s, config) return {} if response.body.nil? || response.body.empty? begin JSON.parse(response.body, symbolize_names: true) rescue JSON::ParserError raise Castle::ApiError, 'Invalid response from Castle API' end end |
.raise_error422(response) ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/castle/core/process_response.rb', line 48 def raise_error422(response) if response.body begin parsed_body = JSON.parse(response.body, symbolize_names: true) if parsed_body.is_a?(Hash) && parsed_body.key?(:type) if parsed_body[:type] == INVALID_REQUEST_TOKEN raise Castle::InvalidRequestTokenError, parsed_body[:message] end raise Castle::InvalidParametersError, parsed_body[:message] end rescue JSON::ParserError end end raise Castle::InvalidParametersError end |
.verify!(response) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/castle/core/process_response.rb', line 36 def verify!(response) return if response.code.to_i.between?(200, 299) raise Castle::InternalServerError if response.code.to_i.between?(500, 599) raise_error422(response) if response.code.to_i == 422 error = RESPONSE_ERRORS.fetch(response.code.to_i, Castle::ApiError) raise error end |