class Camp3::Error::ResponseError

Custom error class for rescuing from HTTP response errors.

Constants

POSSIBLE_MESSAGE_KEYS

Public Class Methods

new(response) click to toggle source
Calls superclass method
# File lib/camp3/error.rb, line 21
def initialize(response)
  @response = response
  super(build_error_message)
end

Public Instance Methods

response_message() click to toggle source

Body content returned in the HTTP response

@return [String]

# File lib/camp3/error.rb, line 36
def response_message
  @response.parsed_response.message
end
response_status() click to toggle source

Status code returned in the HTTP response.

@return [Integer]

# File lib/camp3/error.rb, line 29
def response_status
  @response.code
end

Private Instance Methods

build_error_message() click to toggle source

Human friendly message.

@return [String]

# File lib/camp3/error.rb, line 45
def build_error_message
  parsed_response = classified_response
  message = check_error_keys(parsed_response)
  "Server responded with code #{@response.code}, message: " \
  "#{handle_message(message)}. " \
  "Request URI: #{@response.request.base_uri}#{@response.request.path}"
end
check_error_keys(resp) click to toggle source

Error keys vary across the API, find the first key that the parsed_response object responds to and return that, otherwise return the original.

# File lib/camp3/error.rb, line 55
def check_error_keys(resp)
  key = POSSIBLE_MESSAGE_KEYS.find { |k| resp.respond_to?(k) }
  key ? resp.send(key) : resp
end
classified_response() click to toggle source

Parse the body based on the classification of the body content type

@return parsed response

# File lib/camp3/error.rb, line 63
def classified_response
  if @response.respond_to?('headers')
    @response.headers['content-type'] == 'text/plain' ? { message: @response.to_s } : @response.parsed_response
  else
    @response.parsed_response
  end
rescue Camp3::Error::Parsing
  # Return stringified response when receiving a
  # parsing error to avoid obfuscation of the
  # api error.
  #
  # note: The Camp3 API does not always return valid
  # JSON when there are errors.
  @response.to_s
end
handle_message(message) click to toggle source

Handle error response message in case of nested hashes

# File lib/camp3/error.rb, line 80
def handle_message(message)
  case message
  when Camp3::Resource
    message.to_h.sort.map do |key, val|
      "'#{key}' #{(val.is_a?(Hash) ? val.sort.map { |k, v| "(#{k}: #{v.join(' ')})" } : [val].flatten).join(' ')}"
    end.join(', ')
  when Array
    message.join(' ')
  else
    message
  end
end