Sha256: a753a747dca12fd018db6bd6ef4fc04673f15cfb65e6a2ce9ce5a64c984b6ef9

Contents?: true

Size: 1.44 KB

Versions: 5

Compression:

Stored size: 1.44 KB

Contents

# frozen_string_literal: true

using ObjectExtensions
using StringExtensions

module FinAppsCore
  module Middleware
    class RaiseError < Faraday::Response::Middleware # :nodoc:
      SUCCESS_STATUSES = 200..299
      CONNECTION_FAILED_STATUS = 407
      API_SESSION_TIMEOUT = 419

      def on_complete(env)
        return if SUCCESS_STATUSES.include?(env[:status])

        if env[:status] == API_SESSION_TIMEOUT
          raise(FinAppsCore::Error::ApiSessionTimeoutError, 'Api Session Timed out')
        elsif env[:status] == CONNECTION_FAILED_STATUS
          raise(FinAppsCore::Error::ConnectionFailedError, 'Connection Failed')
        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 empty?(body)
        hash = to_hash body
        messages hash
      end

      def messages(hash)
        return nil unless hash.respond_to?(:key?) && hash.key?('messages')
        hash['messages']
      end

      def to_hash(source)
        return source unless source.is_a?(String)
        source.json_to_hash
      end

      def empty?(o)
        o.nil? || (o.respond_to?(:empty?) && o.empty?)
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
finapps_core-3.0.6 lib/finapps_core/middleware/response/raise_error.rb
finapps_core-3.0.5 lib/finapps_core/middleware/response/raise_error.rb
finapps_core-3.0.3 lib/finapps_core/middleware/response/raise_error.rb
finapps_core-3.0.1 lib/finapps_core/middleware/response/raise_error.rb
finapps_core-2.1.2 lib/finapps_core/middleware/response/raise_error.rb