Sha256: 228d85e6ecdc9cded59253af677cb48079aec90a8d37dafd60495fe1e4ef161f

Contents?: true

Size: 1.13 KB

Versions: 6

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true
module FinApps
  module Middleware
    class RaiseError < Faraday::Response::Middleware # :nodoc:
      using ObjectExtensions
      using StringExtensions

      SUCCESS_STATUSES = 200..299
      CONNECTION_FAILED_STATUS = 407

      def on_complete(env)
        if SUCCESS_STATUSES.include? env[:status]
          # do nothing
        elsif env[:status] == CONNECTION_FAILED_STATUS
          raise(Faraday::Error::ConnectionFailed, '407 "Proxy Authentication Required"')
        else
          raise(Faraday::Error::ClientError, response_values(env))
        end
      end

      def response_values(env)
        {
          status:         env.status,
          headers:        env.response_headers,
          body:           env.body,
          error_messages: error_messages(env.body)
        }
      end

      private

      def error_messages(body)
        return nil if body.blank?
        body = body.json_to_hash if body.is_a?(String)
        has_message_key?(body) ? body['messages'] : nil
      end

      def has_message_key?(body)
        body.respond_to?(:key?) && body.key?('messages')
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
finapps-2.0.30 lib/finapps/middleware/response/raise_error.rb
finapps-2.0.29 lib/finapps/middleware/response/raise_error.rb
finapps-2.0.28 lib/finapps/middleware/response/raise_error.rb
finapps-2.0.27 lib/finapps/middleware/response/raise_error.rb
finapps-2.0.26 lib/finapps/middleware/response/raise_error.rb
finapps-2.0.25 lib/finapps/middleware/response/raise_error.rb