Sha256: c705ab4efc89c86e94f3da0ec5e97ba43ac69231e99d9ab072e77a2c2ba70aa5

Contents?: true

Size: 1.38 KB

Versions: 4

Compression:

Stored size: 1.38 KB

Contents

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

      CLIENT_ERROR_STATUSES = 400...600

      def on_complete(env)
        case env[:status]
        when 407
          # mimic the behavior that we get with proxy requests with HTTPS
          raise Faraday::Error::ConnectionFailed, '407 "Proxy Authentication Required"'
        when CLIENT_ERROR_STATUSES
          raise Faraday::Error::ClientError, response_values(env)
        else
          # 200..206 Success codes
          # all good!
          logger.debug "##{__method__} => Status code: [#{env[:status]}]"
        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 = parse_string(body) if body.is_a?(String)
        body.is_a?(Hash) && body.key?('messages') ? body['messages'] : nil
      end

      def parse_string(body)
        ::JSON.parse(body)
      rescue ::JSON::ParserError
        logger.error "##{__method__} => Unable to parse JSON response."
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
finapps-2.0.13 lib/finapps/middleware/response/raise_error.rb
finapps-2.0.12 lib/finapps/middleware/response/raise_error.rb
finapps-2.0.11 lib/finapps/middleware/response/raise_error.rb
finapps-2.0.10 lib/finapps/middleware/response/raise_error.rb