def safely
    safe_connect

    retries = 0

    begin
      yield

    rescue Errno::ECONNABORTED,
           Errno::ECONNRESET,
           Errno::ENOTCONN,
           Errno::EPIPE,
           Errno::ETIMEDOUT,
           IOError,
           Net::IMAP::ByeResponseError,
           OpenSSL::SSL::SSLError => e

      raise unless (retries += 1) <= @options[:max_retries]

      warning "#{e.class.name}: #{e.message} (reconnecting)"

      reset
      sleep 1 * retries
      safe_connect
      retry

    rescue Net::IMAP::BadResponseError,
           Net::IMAP::NoResponseError,
           Net::IMAP::ResponseParseError => e

      raise unless (retries += 1) <= @options[:max_retries]

      warning "#{e.class.name}: #{e.message} (will retry)"

      sleep 1 * retries
      retry
    end

  rescue Larch::Error => e
    raise

  rescue Net::IMAP::Error => e
    raise Error, "#{e.class.name}: #{e.message} (giving up)"

  rescue => e
    raise FatalError, "#{e.class.name}: #{e.message} (cannot recover)"
  end
def safely
    safe_connect

    retries = 0

    begin
      yield

    rescue Errno::ECONNABORTED,
           Errno::ECONNRESET,
           Errno::ENOTCONN,
           Errno::EPIPE,
           Errno::ETIMEDOUT,
           IOError,
           Net::IMAP::ByeResponseError,
           OpenSSL::SSL::SSLError => e

      raise unless (retries += 1) <= @options[:max_retries]

      warning "#{e.class.name}: #{e.message} (reconnecting)"

      reset
      sleep 1 * retries
      safe_connect
      retry

    rescue Net::IMAP::BadResponseError,
           Net::IMAP::NoResponseError,
           Net::IMAP::ResponseParseError => e

      raise unless (retries += 1) <= @options[:max_retries]

      warning "#{e.class.name}: #{e.message} (will retry)"

      sleep 1 * retries
      retry
    end

  rescue Larch::Error => e
    raise

  rescue Net::IMAP::Error => e
    raise Error, "#{e.class.name}: #{e.message} (giving up)"

  rescue => e
    raise FatalError, "#{e.class.name}: #{e.message} (cannot recover)"
  end
Connect if necessary, execute the given block, retry if a recoverable error
 occurs, die if an unrecoverable error occurs.