Execute the given block with retries and exponential backoff.

 @param [Array<Exception>] rescued
   the list of exceptions to rescue
333568
def with_retries(*rescued, &block)
      options      = rescued.last.is_a?(Hash) ? rescued.pop : {}
      exception    = nil
      retries      = 0

      rescued = Defaults::RETRIED_EXCEPTIONS if rescued.empty?

      max_attempts = options[:attempts] || Defaults::RETRY_ATTEMPTS
      backoff_base = options[:base]     || Defaults::RETRY_BASE
      backoff_max  = options[:max_wait] || Defaults::RETRY_MAX_WAIT

      begin
        return yield retries, exception
      rescue *rescued => e
        exception = e

        retries += 1
        raise if retries > max_attempts

        # Calculate the exponential backoff combined with an element of
        # randomness.
        backoff = [backoff_base * (2 ** (retries - 1)), backoff_max].min
        backoff = backoff * (0.5 * (1 + Kernel.rand))

        # Ensure we are sleeping at least the minimum interval.
        backoff = [backoff_base, backoff].max

        # Exponential backoff.
        Kernel.sleep(backoff)

        # Now retry
        retry
      end
    end
180699
def perform(job)
      begin
        if fork_per_job?
          reconnect
          run_hook :after_fork, job
        end
        job.perform
      rescue Object => e
        report_failed_job(job,e)
      else
        log_with_severity :info, "done: #{job.inspect}"
      ensure
        yield job if block_given?
      end
    end
43205
def CATCH(exception_klass, &block)
      block.call
    rescue ::Exception
      if $!.instance_of? exception_klass
        pass
      else
        failure("Faced a exception, that instance of #{exception_klass}.",
                "Faced a exception, that instance of #{$!.class}.", 2)
      end
    else
      failure("Faced a exception, that instance of #{exception_klass}.",
              'The block was not faced any exceptions.', 2)
    ensure
      _declared!
    end
671452
def upsert(&block)
      ActiveRecord::Base.transaction do
        yield
        @flash_notice = t('save_ok')
      end
      prepare_list
    rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid => ex
      logger.info "#{ex.class.to_s}: #{@record.class.to_s}: #{@record.errors.full_messages.join(' / ')}"
      app_rescue
      @flash_error = t('save_fail')
    end
13772
def checking_exceptions
      yield
    rescue Errno::EACCES => e
      $stderr.puts e
    rescue Errno::ENOENT => e
      $stderr.puts e
    rescue Errno::EEXIST => e
      $stderr.puts e
    rescue NoProjectDirectoryError => e
      $stderr.puts "#{e.directory} is not a tetra project directory, see \"tetra init\""
    rescue GitAlreadyInitedError
      $stderr.puts "This directory is already a tetra project"
    rescue ExecutionFailed => e
      $stderr.puts "Failed to run `#{e.commandline}` (exit status #{e.status})"
    rescue Interrupt
      $stderr.puts "Execution interrupted by the user"
    end
557969
def with_failover #:nodoc:
      end_time = Time.now.to_i + @config.redis_failover_timeout.to_i
      begin
        yield
      rescue Exception => e
        Beetle::reraise_expectation_errors!
        logger.error "Beetle: redis connection error #{e} #{@config.redis_server} (#{e.backtrace[0]})"
        if Time.now.to_i < end_time
          sleep 1
          logger.info "Beetle: retrying redis operation"
          retry
        else
          raise NoRedisMaster.new(e.to_s)
        end
      end
    end
1132954
def execute_with_retries(self, action, f):
        
        # Run action until either it succeeds or throws an exception
        # that's not an ActionRetryException
        retry = True
        while retry:
            retry = False
            try:
                f(action)
            except ActionRetryException as ex:  # other exceptions should bubble out
                retry = True
                time.sleep(ex.ms_backoff / 1000.0)
758607
def wait(retries_left, &blk)
      blk.call
    rescue Exception => e
      retries_left -= 1
      if retries_left > 0
        sleep(0.5)
        retry
      else
        raise
      end
    end
400947
def respond
      inner_error = nil
      rescue_block = proc do |e|
        (env['rack.exception'] = e && raise) unless filters[:error].any? do |f|
          if !f[:args] || f[:args].empty? || f[:args].any? { |type| e.is_a?(type) }
            instance_exec(e, &f[:proc]) unless check_for_failed_condition(f[:conditions])
          end
        end
      end

      begin
        if config[:strip_trailing_slash] == :redirect && request.path =~ %r{[^/]/+$}
          query_string = request.query_string.empty? ? '' : '?' << request.query_string
          redirect(request.path.chomp('/') + query_string, status: 307, halt: false)
          return response.finish
        end
        pass if config[:auto_pass] && eligable_matches.empty?

        if run_filters(:before)
          catch(:halt) {
            begin
              try_matches
            rescue => inner_error
              rescue_block.call(inner_error)
            end
          }
        end
        run_filters(:after)
      rescue => outer_error
        outer_error == inner_error ? raise : catch(:halt) { rescue_block.call(outer_error) }
      end
      response.finish
    end
166439
def capture(options = {})
      if block_given?
        begin
          yield
        rescue Error
          raise # Don't capture Raven errors
        rescue Exception => e
          capture_type(e, options)
          raise
        end
      else
        install_at_exit_hook(options)
      end
    end
537802
def execute!
      exit_code = begin
        # Thor accesses these streams directly rather than letting them be
        # injected, so we replace them...
        $stderr = @stderr
        $stdin = @stdin
        $stdout = @stdout

        VcoWorkflows::CLI.start(@argv)

        # Thor::Base#start does not have a return value, assume success if no
        # exception is raised.
        0
      rescue StandardError => e
        # The ruby interpreter would pipe this to STDERR and exit 1 in the
        # case of an unhandled exception
        b = e.backtrace
        b.unshift("#{b.shift}: #{e.message} (#{e.class})")
        @stderr.puts(b.map { |s| "\tfrom #{s}" }.join("\n"))
        1
      ensure
        # put them back.
        $stderr = STDERR
        $stdin = STDIN
        $stdout = STDOUT
      end
      # Proxy exit code back to the injected kernel.
      @kernel.exit(exit_code)
    end
1060766
def loop_handle_server_calls
      fail 'not started' if running_state == :not_started
      while running_state == :running
        begin
          an_rpc = @server.request_call
          break if (!an_rpc.nil?) && an_rpc.call.nil?
          active_call = new_active_server_call(an_rpc)
          unless active_call.nil?
            @pool.schedule(active_call) do |ac|
              c, mth = ac
              begin
                rpc_descs[mth].run_server_method(
                  c,
                  rpc_handlers[mth],
                  @interceptors.build_context
                )
              rescue StandardError
                c.send_status(GRPC::Core::StatusCodes::INTERNAL,
                              'Server handler failed')
              end
            end
          end
        rescue Core::CallError, RuntimeError => e
          # these might happen for various reasons.  The correct behavior of
          # the server is to log them and continue, if it's not shutting down.
          if running_state == :running
            GRPC.logger.warn("server call failed: #{e}")
          end
          next
        end
      end
      # @running_state should be :stopping here
      @run_mutex.synchronize do
        transition_running_state(:stopped)
        GRPC.logger.info("stopped: #{self}")
        @server.close
      end
    end
1196840
def perform_now
      deserialize_arguments_if_needed
      run_callbacks :perform do
        perform(*arguments)
      end
    rescue => exception
      rescue_with_handler(exception) || raise(exception)
    end
180016
def execute
      puts "Executing #{self.class.taskName} at #{Time::now}".primary
      begin
        self.action
      rescue => e
        puts "Executing #{self.class.taskName} failed".warning
        puts e.inspect.to_s.info
        puts e.backtrace.to_s.info
      end
    end
346874
def run_loop(&block)
      acquired = false
      begin
        until shutdown_pending?
          # The usual situation
          if relock_every != 0
            i ||= 0
            # 0 % anything is 0, so we always try to get the lock on the first loop.
            if (i %= relock_every) == 0
              acquired = lock_function.call(@name)
            end
          else
            # With relock_every set to 0, only acquire the lock once.
            # Hope you're sure that lock beongs to you.
            acquired ||= lock_function.call(@name)
            i = 0 # no point in incrementing something we don't check.
          end

          yield if acquired

          # Sleep one second at a time so we can quickly respond to
          # shutdown requests.
          sleep_for.times do
            sleep(1) unless shutdown_pending?
          end
          i += 1
        end # loop
      rescue ::Interrupt => ex
        log "shutting down after interrupt: #{ex.class} - #{ex.message}"
        shutdown_soon # Always shut down from an Interrupt, even mid-restart.
        return
      rescue ::Exception => ex
        error "restarting after error: #{ex.class} - #{ex.message}"
        error "backtrace: #{ex.backtrace.join("\n")}"
        restart_soon # Restart if we run into an exception.
      end # begin block
    end
1335830
def execute(args = nil)
      execute_task(args)
    rescue Interrupt => e
      raise e # Dont log if it's an interrupt
    rescue Exception => e
      Errdo.error(e, args) if Errdo.log_task_exceptions
      raise e
    end
24130
def rescue_and_retry(fail_message)
        Retriable.retriable(retry_options) do
          return yield
        end
      rescue StandardError => exception
        log_message fail_message
        log_message "Last exception #{exception}"
      end