Whether this task should be retried when the given exception occurs.
438078
def should_retry_on(self, exception_class, logger=None):
        
        for n in (self.retry_on or []):
            try:
                if issubclass(exception_class, import_attribute(n)):
                    return True
            except TaskImportError:
                if logger:
                    logger.error('should_retry_on could not import class',
                                 exception_name=n)
        return False
1260276
@Override
	public void onTaskFailure(Execution taskExecution, Throwable cause) {

		executionGraph.getJobMasterMainThreadExecutor().assertRunningInMainThread();

		// to better handle the lack of resources (potentially by a scale-in), we
		// make failures due to missing resources global failures 
		if (cause instanceof NoResourceAvailableException) {
			LOG.info("Not enough resources to schedule {} - triggering full recovery.", taskExecution);
			executionGraph.failGlobal(cause);
			return;
		}

		LOG.info("Recovering task failure for {} (#{}) via individual restart.", 
				taskExecution.getVertex().getTaskNameWithSubtaskIndex(), taskExecution.getAttemptNumber());

		numTaskFailures.inc();

		// trigger the restart once the task has reached its terminal state
		// Note: currently all tasks passed here are already in their terminal state,
		//       so we could actually avoid the future. We use it anyways because it is cheap and
		//       it helps to support better testing
		final CompletableFuture<ExecutionState> terminationFuture = taskExecution.getTerminalStateFuture();
		terminationFuture.thenRun(
			() -> performExecutionVertexRestart(taskExecution.getVertex(), taskExecution.getGlobalModVersion()));
	}
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
626212
def _should_retry(exc):
    
    if not hasattr(exc, "errors"):
        return False

    if len(exc.errors) == 0:
        # Check for unstructured error returns, e.g. from GFE
        return isinstance(exc, _UNSTRUCTURED_RETRYABLE_TYPES)

    reason = exc.errors[0]["reason"]
    return reason in _RETRYABLE_REASONS
1004564
public synchronized void setFailure(Exception paramE) {
        if (done)
            return; // can't mark done twice
        e = paramE;
        done = true;
        notifyAll();

        // if we have a callback to call, schedule
        // it on a different thread. Who knows what this
        // thread is doing.
        if (callback != null) {
            QueueBuffer.executor.submit(new Callable<Void>() {
                public Void call() throws Exception {
                    callback.onError(e);
                    return null;
                }
            });

        }

    }
865573
public static void call(Runnable task) {
        try {
            call(() -> {
                task.run();
                return true;
            });
        } catch (Exception e) {
            // It's safe to throw unsafely here because the Callable we passed never throws a checked exception.
            Exceptions.throwUnsafely(e);
        }
    }
295657
private boolean isRetryException(final Throwable th) {
        Throwable current = th;
        boolean res = false;
        while (current != null) {
            if (current instanceof ONeedRetryException) {
                res = true;
                break;
            }
            current = current.getCause();
        }
        return res;
    }
1067190
def on_failure(self, exc, task_id, args, kwargs, einfo):
        
        key = self._get_cache_key(args, kwargs)
        _, penalty = cache.get(key, (0, 0))
        if penalty < self.MAX_PENALTY:
            penalty += 1

        logger.debug('The task %s is penalized and will be executed on %d run.' % (self.name, penalty))
        cache.set(key, (penalty, penalty), self.CACHE_LIFETIME)
        return super(PenalizedBackgroundTask, self).on_failure(exc, task_id, args, kwargs, einfo)
1289503
@Override
	public void onTaskFailure(Execution taskExecution, Throwable cause) {
		final ExecutionVertex ev = taskExecution.getVertex();
		final FailoverRegion failoverRegion = vertexToRegion.get(ev);

		if (failoverRegion == null) {
			executionGraph.failGlobal(new FlinkException(
					"Can not find a failover region for the execution " + ev.getTaskNameWithSubtaskIndex(), cause));
		}
		else {
			LOG.info("Recovering task failure for {} #{} ({}) via restart of failover region",
					taskExecution.getVertex().getTaskNameWithSubtaskIndex(),
					taskExecution.getAttemptNumber(),
					taskExecution.getAttemptId());

			failoverRegion.onExecutionFail(taskExecution, cause);
		}
	}
2267
public static <T> T retry(final Callable<T> f, Predicate<Throwable> shouldRetry, final int maxTries) throws Exception
  {
    return retry(f, shouldRetry, 0, maxTries);
  }
48597
public void         takeException(Exception exception) throws Exception
    {
        Preconditions.checkState(Thread.currentThread().equals(ourThread), "Not in the correct thread");

        boolean     passUp = true;
        if ( sessionHasFailed.get() )
        {
            switch ( mode )
            {
                case RETRY:
                {
                    sessionHasFailed.set(false);
                    failedSessionThreads.remove(ourThread);
                    if ( exception instanceof SessionFailedException )
                    {
                        isDone.set(false);
                        passUp = false;
                    }
                    break;
                }

                case FAIL:
                {
                    break;
                }
            }
        }

        if ( passUp )
        {
            retryLoop.takeException(exception);
        }
    }
9366
private boolean isRetryable(Exception e)
	  {
	    final String mName = "isRetryable";

	    String exClassName = e.getClass().getName();
	    
	    boolean retVal = containsException(_retryIncludeExceptions, e) && !containsException(_retryExcludeExceptions, e);
	    
	    if(logger.isLoggable(Level.FINE)) 
	      logger.logp(Level.FINE, className, mName, mName + ": " + retVal + ": " + exClassName);

	    return retVal;
	  }
780884
private void checkAndPropagateAsyncError() throws Exception {
		if (thrownException != null) {
			String errorMessages = "";
			if (thrownException instanceof UserRecordFailedException) {
				List<Attempt> attempts = ((UserRecordFailedException) thrownException).getResult().getAttempts();
				for (Attempt attempt: attempts) {
					if (attempt.getErrorMessage() != null) {
						errorMessages += attempt.getErrorMessage() + "\n";
					}
				}
			}
			if (failOnError) {
				throw new RuntimeException("An exception was thrown while processing a record: " + errorMessages, thrownException);
			} else {
				LOG.warn("An exception was thrown while processing a record: {}", thrownException, errorMessages);

				// reset, prevent double throwing
				thrownException = null;
			}
		}
	}
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
262876
public void handleException(TaskCommand<String,String> taskCommand, Exception exception){
		try {
			exception(taskCommand, exception);
		}
		catch (Exception e){
			logger.warn("Handle Task Exception failed:",e);
		}
	}
1310675
public void abort(Throwable t) {
        // Set the result to the given exception
        boolean abortSuccessful = getResultFuture().completeExceptionally(t);

        if (abortSuccessful) {
            // Attempt to abort the task
            getTaskFuture().cancel(true);
        }
    }
582623
def _execute_handling(self, *eopatches, **kwargs):
        
        self.private_task_config.start_time = datetime.datetime.now()

        caught_exception = None
        try:
            return_value = self.execute(*eopatches, **kwargs)
        except BaseException as exception:
            caught_exception = exception, sys.exc_info()[2]

        if caught_exception is not None:  # Exception is not raised in except statement to prevent duplicated traceback
            exception, traceback = caught_exception
            raise type(exception)('During execution of task {}: {}'.format(self.__class__.__name__,
                                                                           exception)).with_traceback(traceback)

        self.private_task_config.end_time = datetime.datetime.now()
        return return_value