Sha256: b51d4747b9fd0ae7cd0d2b3d888982f8b26b76751142209b499f737baa57530f

Contents?: true

Size: 1.48 KB

Versions: 1

Compression:

Stored size: 1.48 KB

Contents

# frozen_string_literal: true

module Usps
  module Imis
    module Error
      class Api < StandardError
        attr_reader :response
        attr_accessor :metadata

        def self.from(response)
          new('The iMIS API returned an error.', response)
        end

        def initialize(message, response, metadata = {})
          super(message)
          @metadata = metadata
          @response = response
        end

        def bugsnag_meta_data
          { api: { status: status, body: body }.merge!(metadata) }
        end

      private

        def status
          @status ||=
            case response.code
            when '400'
              :bad_request
            when '401'
              :unauthorized # RequestVerificationToken invalid
            when '404'
              :not_found
            when '422'
              :unprocessable_entity # validation error
            when /^50\d$/
              :internal_server_error # error within iMIS
            end
        end

        def response_body
          @response_body ||= JSON.parse(response.body)
        rescue StandardError
          @response_body ||= response.body
        end

        def body
          return response_body unless response_body.is_a?(Hash)

          case response_body['error']
          when 'invalid_grant'
            response_body['error_description']
          else
            # Unknown error type: just use the raw response
            response.body
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
usps-imis-api-0.3.0 lib/usps/imis/error/api.rb