Queue failed Solr calls with Delayed::Job

We are using websolr.com from one of our Heroku apps and from time to time we see connection errors. This is disruptive in the UI. One option was to move all of the Solr calls to DJ tasks, but I didn’t want to have a ton of stuff in the DJ queue. The other option was to make a variation of SilentFailSessionProxy and have it queue up the jobs we cared about, specifically index and remove and raise the others.

Here is the current version of this.

require 'sunspot/session_proxy/silent_fail_session_proxy'

module Sunspot
  module SessionProxy
    class QueueFailureSessionProxy < Sunspot::SessionProxy::SilentFailSessionProxy
      QUEUE_METHODS = [:index!, :index, :remove!, :remove]

      def rescued_exception(method_name, ex, klass)
        raise ex unless ::Rails.env.production?

        if klass && QUEUE_METHODS.include?(method_name)
          HoptoadNotifier.notify(
            :error_class => "Solr Exception",
            :error_message => "Solr Exception: #{ex.message}",
            :parameters => { :model => klass, :method => method_name }
          ) if defined?(HoptoadNotifier)

          klass.delay.index! if method_name.to_s.match('index')
          klass.delay.remove_from_index! if method_name.to_s.match('remove')
        else
          raise ex
        end
      end

      SUPPORTED_METHODS.each do |method|
        module_eval(<<-RUBY)
          def #{method}(*args, &block)
            begin
              search_session.#{method}(*args, &block)
            rescue => ex
              self.rescued_exception(:#{method}, ex, args.first)
            end
          end
        RUBY
      end

    end
  end
end

Sunspot.session = Sunspot::SessionProxy::QueueFailureSessionProxy.new(Sunspot.session)