lib/patiently_try.rb in patiently_try-0.1.1 vs lib/patiently_try.rb in patiently_try-0.2.0
- old
+ new
@@ -1,25 +1,49 @@
require "patiently_try/version"
module PatientlyTry
def patiently_try(opts = {})
- retries = opts[:retries] || 100
- wait = opts[:wait] || 0
- catch_errors = opts[:catch] || StandardError
- logging = opts[:logging].nil? ? true : opts[:logging]
- try = 0
+ retries = opts[:retries] || 100
+ wait = opts[:wait] || 0
+ catch_errors = Array(opts[:catch] || StandardError)
+ excluded_errors = Array(opts[:raise_if_caught])
+ logging = opts[:logging].nil? ? true : opts[:logging]
+ try = 0
begin
yield
- rescue *(Array(catch_errors)) => e
+ rescue *(catch_errors) => e
try += 1
- puts "Failed with: #{e.inspect}" if logging
- raise e if try >= retries
+ _log_error if logging
- puts "Retrying (#{try}/#{retries})"
+ if try >= retries || _rescued_but_excluded?(e, excluded_errors)
+ _log_backtrace if logging
+ raise e
+ end
+
+ _log_retry if logging
+
sleep wait if wait && wait > 0
retry
end
+ end
+
+ private
+
+ def _log_retry
+ puts "Retrying (#{try}/#{retries})"
+ end
+
+ def _rescued_but_excluded?(e, excluded_errors)
+ excluded_errors.to_a.inject(false) { |excl, error| excl || e.is_a?(error) }
+ end
+
+ def _log_error(e)
+ puts "Failed with: #{e.inspect}"
+ end
+
+ def _log_backtrace(e)
+ puts e.backtrace.join("\n")
end
end