Returns true if should retry based on the passed-in exception.

        :param (errors.HTTPFailure instance) exception:

        :rtype:
            boolean
517844
def ShouldRetry(self, exception):
        
        if self.current_retry_attempt_count < self._max_retry_attempt_count:
            self.current_retry_attempt_count += 1
            self.retry_after_in_milliseconds = 0
                
            if self._fixed_retry_interval_in_milliseconds:
                self.retry_after_in_milliseconds = self._fixed_retry_interval_in_milliseconds
            elif http_constants.HttpHeaders.RetryAfterInMilliseconds in exception.headers:
                self.retry_after_in_milliseconds = int(exception.headers[http_constants.HttpHeaders.RetryAfterInMilliseconds])
                
            if self.cummulative_wait_time_in_milliseconds < self._max_wait_time_in_milliseconds:
                self.cummulative_wait_time_in_milliseconds += self.retry_after_in_milliseconds
                return True
            
        return False
282
def retry(self):
        

        if self.connector is None:
            raise ValueError("No connector to retry")
        if self.service is None:
            return
        self.connector.connect()
123502
def is_error_retryable(request, exc):
    
    if is_last_attempt(request):
        return False

    return (
        isinstance(exc, RetryableException)
        or IRetryableError.providedBy(exc)
    )
473711
def _call_retry(self, force_retry):
        """"""
        last_exception = None
        for i in range(self.max_attempts):
            try:
                log.info("Calling %s %s" % (self.method, self.url))
                response = self.requests_method(
                    self.url,
                    data=self.data,
                    params=self.params,
                    headers=self.headers,
                    timeout=(self.connect_timeout, self.read_timeout),
                    verify=self.verify_ssl,
                )

                if response is None:
                    log.warn("Got response None")
                    if self._method_is_safe_to_retry():
                        delay = 0.5 + i * 0.5
                        log.info("Waiting %s sec and Retrying since call is a %s" % (delay, self.method))
                        time.sleep(delay)
                        continue
                    else:
                        raise PyMacaronCoreException("Call %s %s returned empty response" % (self.method, self.url))

                return response

            except Exception as e:

                last_exception = e

                retry = force_retry

                if isinstance(e, ReadTimeout):
                    # Log enough to help debugging...
                    log.warn("Got a ReadTimeout calling %s %s" % (self.method, self.url))
                    log.warn("Exception was: %s" % str(e))
                    resp = e.response
                    if not resp:
                        log.info("Requests error has no response.")
                        # TODO: retry=True? Is it really safe?
                    else:
                        b = resp.content
                        log.info("Requests has a response with content: " + pprint.pformat(b))
                    if self._method_is_safe_to_retry():
                        # It is safe to retry
                        log.info("Retrying since call is a %s" % self.method)
                        retry = True

                elif isinstance(e, ConnectTimeout):
                    log.warn("Got a ConnectTimeout calling %s %s" % (self.method, self.url))
                    log.warn("Exception was: %s" % str(e))
                    # ConnectTimeouts are safe to retry whatever the call...
                    retry = True

                if retry:
                    continue
                else:
                    raise e

        # max_attempts has been reached: propagate the last received Exception
        if not last_exception:
            last_exception = Exception("Reached max-attempts (%s). Giving up calling %s %s" % (self.max_attempts, self.method, self.url))
        raise last_exception
991769
def ShouldRetry(self, exception):
        
        if not self.connection_policy.EnableEndpointDiscovery:
            return False

        if self.failover_retry_count >= self.Max_retry_attempt_count:
            return False

        self.failover_retry_count += 1

        if self.location_endpoint:
            if _OperationType.IsReadOnlyOperation(self.request.operation_type):
                #Mark current read endpoint as unavailable
                self.global_endpoint_manager.mark_endpoint_unavailable_for_read(self.location_endpoint)
            else:
                self.global_endpoint_manager.mark_endpoint_unavailable_for_write(self.location_endpoint)

        # set the refresh_needed flag to ensure that endpoint list is
        # refreshed with new writable and readable locations
        self.global_endpoint_manager.refresh_needed = True
        
        # clear previous location-based routing directive
        self.request.clear_route_to_location()

        # set location-based routing directive based on retry count
        # simulating single master writes by ensuring usePreferredLocations
        # is set to false
        self.request.route_to_location_with_preferred_location_flag(self.failover_retry_count, False)
        
        # Resolve the endpoint for the request and pin the resolution to the resolved endpoint
        # This enables marking the endpoint unavailability on endpoint failover/unreachability
        self.location_endpoint = self.global_endpoint_manager.resolve_service_endpoint(self.request)
        self.request.route_to_location(self.location_endpoint)
        return True
658012
def _handle_retryable_error(self, e, retry_count):
        """"""
        if isinstance(e, error.RateLimitEnforcedError):
            time.sleep(e.retry_after)
        else:
            time.sleep(self.RETRY_DELAY * (self.RETRY_BACKOFF ** retry_count))
881021
def exception_retry_middleware(make_request, web3, errors, retries=5):
    
    def middleware(method, params):
        if check_if_retry_on_failure(method):
            for i in range(retries):
                try:
                    return make_request(method, params)
                except errors:
                    if i < retries - 1:
                        continue
                    else:
                        raise
        else:
            return make_request(method, params)
    return middleware
1246678
def _should_retry(self, context):
        # type: (ExponentialRetryWithMaxWait,
        #        azure.storage.common.models.RetryContext) -> bool
        
        # do not retry if max attempts equal or exceeded
        if context.count >= self.max_attempts:
            return False

        # get response status
        status = None
        if context.response and context.response.status:
            status = context.response.status

        # if there is no response status, then handle the exception
        # appropriately from the lower layer
        if status is None:
            exc = context.exception
            # default to not retry in unknown/unhandled exception case
            ret = False
            # requests timeout, retry
            if isinstance(exc, requests.Timeout):
                ret = True
            elif isinstance(exc, requests.exceptions.ContentDecodingError):
                ret = True
            elif (isinstance(exc, requests.exceptions.ConnectionError) or
                  isinstance(exc, requests.exceptions.ChunkedEncodingError)):
                # newer versions of requests do not expose errno on the
                # args[0] reason object; manually string parse
                if isinstance(exc.args[0], urllib3.exceptions.MaxRetryError):
                    try:
                        msg = exc.args[0].reason.args[0]
                    except (AttributeError, IndexError):
                        # unexpected/malformed exception hierarchy, don't retry
                        pass
                    else:
                        if any(x in msg for x in _RETRYABLE_ERRNO_MAXRETRY):
                            ret = True
                elif isinstance(exc.args[0], urllib3.exceptions.ProtocolError):
                    try:
                        msg = exc.args[0].args[0]
                    except (AttributeError, IndexError):
                        # unexpected/malformed exception hierarchy, don't retry
                        pass
                    else:
                        if any(x in msg for x in _RETRYABLE_ERRNO_PROTOCOL):
                            ret = True
            # fallback to string search
            if not ret:
                msg = str(exc).lower()
                if any(x in msg for x in _RETRYABLE_STRING_FALLBACK):
                    ret = True
            return ret
        elif 200 <= status < 300:
            # failure during respond body download or parsing, so success
            # codes should be retried
            return True
        elif 300 <= status < 500:
            # response code 404 should be retried if secondary was used
            if (status == 404 and
                    context.location_mode ==
                    azure.storage.common.models.LocationMode.SECONDARY):
                return True
            # response code 408 is a timeout and should be retried
            # response code 429 is too many requests (throttle)
            # TODO use "Retry-After" header for backoff amount
            if status == 408 or status == 429:
                return True
            return False
        elif status >= 500:
            # response codes above 500 should be retried except for
            # 501 (not implemented) and 505 (version not supported)
            if status == 501 or status == 505:
                return False
            return True
        else:  # noqa
            # this should be unreachable, retry anyway
            return True
586909
async def retry_async(self, func, partition_id, retry_message,
                          final_failure_message, max_retries, host_id):
        
        created_okay = False
        retry_count = 0
        while not created_okay and retry_count <= max_retries:
            try:
                await func(partition_id)
                created_okay = True
            except Exception as err:  # pylint: disable=broad-except
                _logger.error("%r %r %r %r", retry_message, host_id, partition_id, err)
                retry_count += 1
        if not created_okay:
            raise Exception(host_id, final_failure_message)
1254657
def retry_on_excs(excs, retry_count=3, delay=5):
    

    def wrapper(f):
        @functools.wraps(f)
        def deco(*args, **kwargs):
            for i in range(0, retry_count):
                try:
                    return f(*args, **kwargs)
                except excs:
                    if logger:
                        logger.warning(
                            'HTTPError caught.Retrying ...'.format(f.__name__),
                            exc_info=True
                        )
                    time.sleep(delay)
            else:
                logger.error(
                    '{} failed after {} retries'.format(
                        f.__name__, retry_count)
                )
            return f(*args, **kwargs)

        return deco

    return wrapper
1323370
def create_failure(self, exception=None):
        
        if exception:
            return FailedFuture(type(exception), exception, None)
        return FailedFuture(*sys.exc_info())
886532
def _retry_failed_log(failed_trigger_log):
    
    model = type(failed_trigger_log)
    try:
        failed_trigger_log = (
            model.objects
            .select_for_update()
            .get(
                id=failed_trigger_log.id,
                state=TRIGGER_LOG_STATE['FAILED'],
            )
        )
    except model.DoesNotExist:
        return False
    failed_trigger_log.redo()
    return True
557034
def has_succeed(self):
        
        status_code = self._response.status_code

        if status_code in [HTTP_CODE_ZERO, HTTP_CODE_SUCCESS, HTTP_CODE_CREATED, HTTP_CODE_EMPTY, HTTP_CODE_MULTIPLE_CHOICES]:
            return True

        if status_code in [HTTP_CODE_BAD_REQUEST, HTTP_CODE_UNAUTHORIZED, HTTP_CODE_PERMISSION_DENIED, HTTP_CODE_NOT_FOUND, HTTP_CODE_METHOD_NOT_ALLOWED, HTTP_CODE_CONNECTION_TIMEOUT, HTTP_CODE_CONFLICT, HTTP_CODE_PRECONDITION_FAILED, HTTP_CODE_INTERNAL_SERVER_ERROR, HTTP_CODE_SERVICE_UNAVAILABLE]:
            return False

        raise Exception('Unknown status code %s.', status_code)
756668
def _fail_if_contains_errors(response, sync_uuid=None):
    
    if response.status_code != _HTTP_OK:
        raise RequestError(response)
    response_json = response.json()
    if sync_uuid and 'sync_status' in response_json:
        status = response_json['sync_status']
        if sync_uuid in status and 'error' in status[sync_uuid]:
            raise RequestError(response)
608627
def retry(func, exception_type, quit_event):
    
    while True:
        if quit_event.is_set():
            raise StopIteration
        try:
            return func()
        except exception_type:
            pass
1328608
public static boolean isRetryableServiceException(AmazonServiceException exception) {
        return RETRYABLE_STATUS_CODES.contains(exception.getStatusCode()) ||
               RETRYABLE_ERROR_CODES.contains(exception.getErrorCode());
    }
655626
def retry_after(cls, response, default=5, _now=time.time):
        
        val = response.headers.getRawHeaders(b'retry-after', [default])[0]
        try:
            return int(val)
        except ValueError:
            return http.stringToDatetime(val) - _now()