Sha256: 4f1d94a81b69369c6e1f83d29f8e3072b197f3190136afef99520eae9e1cb29c

Contents?: true

Size: 959 Bytes

Versions: 2

Compression:

Stored size: 959 Bytes

Contents

# frozen_string_literal: true

module FriendlyShipping
  module Services
    class ShipEngine
      # Raised when an API error is returned.
      class ApiError < FriendlyShipping::ApiError
        # @param cause [RestClient::Exception] the cause of the error
        def initialize(cause)
          super(cause, parse_message(cause))
        end

        private

        # Parses the message from the error response.
        #
        # @param error [RestClient::Exception] the cause of the error
        # @return [String, nil] the message or nil if it couldn't be parsed
        def parse_message(error)
          return error.message unless error.response && error.http_code == 400

          parsed_body = JSON.parse(error.response.body)
          messages = parsed_body.fetch('errors')&.map { |e| e.fetch('message') }
          messages&.join(', ')
        rescue JSON::ParserError, KeyError => _e
          nil
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
friendly_shipping-0.10.1 lib/friendly_shipping/services/ship_engine/api_error.rb
friendly_shipping-0.10.0 lib/friendly_shipping/services/ship_engine/api_error.rb