Sha256: 23e5887fc0249ca6ee7ec6cf65d05f802e8172646e1b258f2f8222382a28fe69

Contents?: true

Size: 998 Bytes

Versions: 1

Compression:

Stored size: 998 Bytes

Contents

# frozen_string_literal: true

require 'friendly_shipping/api_error'

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

1 entries across 1 versions & 1 rubygems

Version Path
friendly_shipping-0.9.0 lib/friendly_shipping/services/ship_engine/api_error.rb