Sha256: a03cd5ab428dda51b71da593ad6e4b701d153013b16d4c8434daf7e75a571c4d

Contents?: true

Size: 1.3 KB

Versions: 5

Compression:

Stored size: 1.3 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 !body || (body.respond_to?(:empty?) && body.empty?)
        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

5 entries across 5 versions & 1 rubygems

Version Path
finapps_core-2.0.20 lib/finapps_core/middleware/response/raise_error.rb
finapps_core-2.0.19 lib/finapps_core/middleware/response/raise_error.rb
finapps_core-2.0.18 lib/finapps_core/middleware/response/raise_error.rb
finapps_core-2.0.17 lib/finapps_core/middleware/response/raise_error.rb
finapps_core-2.0.16 lib/finapps_core/middleware/response/raise_error.rb