Sha256: 68af98a0b6acda08ad83c17718f14b9026d5eb0f9e4d91b6015c6a25d7f36c9e

Contents?: true

Size: 1.35 KB

Versions: 5

Compression:

Stored size: 1.35 KB

Contents

# frozen_string_literal: true

require "http"

module Mihari
  module HTTP
    #
    # Better error handling feature
    #
    class BetterError < ::HTTP::Feature
      def wrap_response(response)
        return response if response.status.success?

        raise StatusCodeError.new(
          "Unsuccessful response code returned: #{response.code}",
          response.code,
          response.body.to_s
        )
      end

      def on_error(_request, error)
        raise TimeoutError, error if error.is_a?(::HTTP::TimeoutError)
        raise NetworkError, error if error.is_a?(::HTTP::Error)
      end

      ::HTTP::Options.register_feature(:better_error, self)
    end

    #
    # HTTP client factory
    #
    class Factory
      class << self
        USER_AGENT = "mihari/#{Mihari::VERSION}".freeze
        #
        # @param [Integer, nil] timeout
        # @param [Hash] headers
        # @param [Boolean] raise_exception
        #
        # @return [::HTTP::Client]
        #
        # @param [Object] raise_exception
        def build(headers: {}, timeout: nil, raise_exception: true)
          client = raise_exception ? ::HTTP.use(:better_error) : ::HTTP

          headers["User-Agent"] ||= USER_AGENT

          client = client.headers(headers)
          client = client.timeout(timeout) unless timeout.nil?
          client
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
mihari-7.0.4 lib/mihari/http.rb
mihari-7.0.3 lib/mihari/http.rb
mihari-7.0.2 lib/mihari/http.rb
mihari-7.0.1 lib/mihari/http.rb
mihari-7.0.0 lib/mihari/http.rb