Sha256: 7f09e1c7a6fc5a268fbfcb8f1f600227b80868cdc0049604918287f2f972c494

Contents?: true

Size: 948 Bytes

Versions: 3

Compression:

Stored size: 948 Bytes

Contents

require 'json'

# ApiClient::Parser provides a method to parse the request response.
module ApiClient::Parser
  # Parse the JSON response.
  #
  # @param [HTTP] response HTTP object for the request.
  # @return [Hash] the body parsed.
  def self.response(response, url)
    raise_exception(response, url)
    begin
      object = ::JSON.parse(response.body)
    rescue ::JSON::ParserError, TypeError
      object = {}
    end
    object
  end

  protected

  def self.raise_exception(response, url)
    case response.code.to_i
      when 401 then raise ApiClient::Exceptions::Unauthorized
      when 403 then raise ApiClient::Exceptions::Forbidden
      when 404 then raise ApiClient::Exceptions::NotFound.new(url)
      when 500 then raise ApiClient::Exceptions::InternalServerError
      when 502 then raise ApiClient::Exceptions::BadGateway
      when 503 then raise ApiClient::Exceptions::ServiceUnavailable
      else return
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
api-client-2.0.0.rc1 lib/api-client/parser.rb
api-client-1.10.0 lib/api-client/parser.rb
api-client-1.9.1 lib/api-client/parser.rb