Sha256: f7943c1a46bb88a60b2d5b1dc571a419331de2f51194d333d4f1490bd4efa106

Contents?: true

Size: 1.38 KB

Versions: 5

Compression:

Stored size: 1.38 KB

Contents

module NxtHttpClient
  class Error < StandardError
    def initialize(response)
      @response = response.blank? ? Typhoeus::Response.new : response
    end

    attr_reader :response

    def to_s
      "NxtHttpClient::Error::#{response_code}"
    end

    def to_h
      {
        url: url,
        response_code: response_code,
        request_options: request_options,
        response_headers: response_headers,
        body: body
      }
    end

    def body
      if response_content_type == 'application/json'
        JSON.parse(response.body)
      else
        response.body
      end
    rescue ::JSON::JSONError
      response.body
    end

    def response_code
      response.code || 0
    end

    def request
      @request ||= response.request || Typhoeus::Request.new('/dev/null', {})
    end

    def url
      request.url
    end

    def request_options
      @request_options ||= (request.original_options || {}).with_indifferent_access
    end

    def request_headers
      @request_headers ||= (request.original_options[:headers] || {}).with_indifferent_access
    end

    def response_options
      @response_options ||= (response.options || {}).with_indifferent_access
    end

    def response_headers
      @response_headers ||= (response.headers || {}).with_indifferent_access
    end

    def response_content_type
      response_headers['Content-Type']
    end
  end
end


Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
nxt_http_client-0.2.9 lib/nxt_http_client/error.rb
nxt_http_client-0.2.8 lib/nxt_http_client/error.rb
nxt_http_client-0.2.7 lib/nxt_http_client/error.rb
nxt_http_client-0.2.6 lib/nxt_http_client/error.rb
nxt_http_client-0.2.5 lib/nxt_http_client/error.rb