spree_active_shipping icon indicating copy to clipboard operation
spree_active_shipping copied to clipboard

ActiveUtils::ConnectionError

Open jkelleyj opened this issue 5 years ago • 1 comments

Whenever the USPS rate api goes down (which is a surprisingly regular occurrence https://www.shippingapimonitor.com/history.html?api=usps), ActiveUtils will raise an ActiveUtils::ConnectionError that we don't handle today. Most other Active Shipping response errors are handled and reraised, but this one bubble up and can prevent checkout.

I'm patching our installation with the following extension and wonder if you guys think it would be worth submitting a PR.

module Spree
  module Calculator::Shipping
    module ActiveShipping
      module BaseExtensions

        # Catch low lying ActiveUtils error from ActiveShipping - not handled by spree extension.
        # This happens when the USPS api goes down. Reraise as ShippingError for proper handling.
        def retrieve_rates(origin, destination, shipment_packages)
          begin
            super
          rescue ::ActiveUtils::ConnectionError => e
            error = Spree::ShippingError.new("#{I18n.t(:shipping_error)}: It looks like we are unable to lookup shipping rates for this service right now.")
            Rails.cache.write @cache_key, error, expires_in: 10.minutes
            raise error
          end
        end
      end
    end
  end
end

Since USPS Base has it's own retrieve rates method, we need to prepend on it as well as the overall ActiveShipping Base.

Spree::Calculator::Shipping::Usps::Base.class_eval do
  prepend Spree::Calculator::Shipping::ActiveShipping::BaseExtensions
end
Spree::Calculator::Shipping::ActiveShipping::Base.class_eval do
  prepend Spree::Calculator::Shipping::ActiveShipping::BaseExtensions
end

Anybody see any issues or better approaches to solve this?

jkelleyj avatar Aug 29 '18 15:08 jkelleyj

I followed the pattern in the retrieve_rates method to set a cache value to prevent frequent retries on this order. I added a 10 minute expiration so the order could get rates in the future if they do not complete now, however we could easily discard this optimization as it breaks from the pattern in the base classes.

jkelleyj avatar Aug 29 '18 16:08 jkelleyj