Mark a job as Failed, incrementing the failed-counter and Requeueing it.

@param \Queue\Model\Entity\QueuedJob $job Job
@param string|null $failureMessage Optional message to append to the failure_message field.
@return bool Success
183481
public function markJobFailed(QueuedJob $job, $failureMessage = null) {
		$fields = [
			'failed' => $job->failed + 1,
			'failure_message' => $failureMessage,
		];
		$job = $this->patchEntity($job, $fields);

		return (bool)$this->save($job);
	}
30462
protected function failJob($job, $e)
    {
        if ($job->isDeleted()) {
            return;
        }
        $job->delete();
        $job->failed($e);
    }
895858
public function executeJob(Job $job, int $retryLimit = 0): void
    {
        // This is here so that if executeJob is called with out startBatch the events will still be called
        $this->triggerBatchEvents = !$this->batchStarted;
        if ($this->triggerBatchEvents) {
            $this->startBatch(new JobBatch([$job]));
        }

        $internal = false;

        if ($this->logger) {
            $this->logger->debug('Start a job.', [
                'name' => $job->getName(),
                'arguments' => $job->getArguments(),
            ]);
        }

        try {
            $worker = $this->workersMap->get($job->getName());
            if (!$worker instanceof Worker) {
                throw new InvalidWorkerException("The worker {$job->getName()} is not an instance of ".Worker::class);
            }
            $internal = $worker instanceof InternalWorker;
            if ($this->eventDispatcher) {
                $this->eventDispatcher->dispatch(self::JOB_START_EVENT, new StartJobEvent($job, $internal));
            }
            $worker->execute($job->getArguments());
        } catch (NotFoundExceptionInterface $e) {
            $unrecoverable = new UnrecoverableJobException("Missing worker {$job->getName()}", 0, $e);
            $this->failedJob($job, $unrecoverable, $internal);

            throw $unrecoverable;
        } catch (UnrecoverableJobExceptionInterface $e) {
            $this->failedJob($job, $e, $internal);

            throw $e;
        } catch (\Throwable $e) {
            if (!$job instanceof RetryableJob) {
                $unrecoverable = new UnrecoverableJobException('Job failed and is not retryable', 0, $e);
                $this->failedJob($job, $unrecoverable, $internal);

                throw $unrecoverable;
            }

            if ($job->getRetryCount() >= $retryLimit) {
                $unrecoverable = new UnrecoverableJobException('Job reached retry limit and won\'t be retried again', 0, $e);
                $this->failedJob($job, $unrecoverable, $internal);

                throw $unrecoverable;
            }

            $this->failedJob($job, $e, $internal);

            throw $e;
        }
        $this->finishJob($job, $internal);
    }
66732
protected function failed()
    {
        $retryCount = $this->model->getTriedCount() + 1;

        if ($retryCount >= $this->getMaxRetryCount()) {
            $this->model->setStatus(JobsConst::JOB_STATUS_FAILED);
        } else {
            $this->model->setStatus(JobsConst::JOB_STATUS_WAITING_RETRY);
            $this->model->setTryAt($this->getNextTryTime());
        }
        $this->model->setTriedCount($retryCount);

        return $this->model->persist();
    }
81352
public static function handle($connectionName, $job, $e = null)
    {
        $job->markAsFailed();

        if ($job->isDeleted()) {
            return;
        }

        try {
            // If the job has failed, we will delete it, call the "failed" method and then call
            // an event indicating the job has failed so it can be logged if needed. This is
            // to allow every developer to better keep monitor of their failed queue jobs.
            $job->delete();

            $job->failed($e);
        } finally {
            static::events()->dispatch(new JobFailed(
                $connectionName, $job, $e ?: new ManuallyFailedException()
            ));
        }
    }
813729
public static function handle($connectionName, $job, $e = null)
    {
        $job->markAsFailed();

        if ($job->isDeleted()) {
            return;
        }

        try {
            // If the job has failed, we will delete it, call the "failed" method and then call
            // an event indicating the job has failed so it can be logged if needed. This is
            // to allow every developer to better keep monitor of their failed queue jobs.
            $job->delete();

            $job->failed($e);

        } finally {
        }
    }
526454
public function perform(Resque_Job $job)
	{
		try {
			Resque_Event::trigger('afterFork', $job);
			$job->perform();
		}
		catch(Exception $e) {
			$this->logger->log(Psr\Log\LogLevel::CRITICAL, '{job} has failed {stack}', array('job' => $job, 'stack' => $e));
			$job->fail($e);
			return;
		}

		$job->updateStatus(Resque_Job_Status::STATUS_COMPLETE);
		$this->logger->log(Psr\Log\LogLevel::NOTICE, '{job} has finished', array('job' => $job));
	}
1169506
protected function failed($e)
    {
        $payload = $this->payload();

        [$class, $method] = JobName::parse($payload['job']);

        if (method_exists($this->instance = $this->resolve($class), 'failed')) {
            $this->instance->failed($payload['data'], $e);
        }
    }
544797
protected function logFailedJob(JobFailed $event)
    {
        $this->app['queue.failer']->log(
            $event->connector, $event->job->getQueue(),
            $event->job->getRawBody(), $event->exception
        );
    }
986748
public function destroy(JobRequest $request, Job $job)
    {
        try {

            $job->delete();
            return $this->response->message(trans('messages.success.deleted', ['Module' => trans('career::job.name')]))
                ->code(202)
                ->status('success')
                ->url(guard_url('career/job/0'))
                ->redirect();

        } catch (Exception $e) {

            return $this->response->message($e->getMessage())
                ->code(400)
                ->status('error')
                ->url(guard_url('career/job/' . $job->getRouteKey()))
                ->redirect();
        }

    }
1157639
private function failJob(JobInterface $job, Exception $reason = null, $silent = true)
    {
        if ($job_id = $job->getQueueId()) {
            $previous_attempts = $this->getPreviousAttemptsByJobId($job_id);

            $log_arguments = [
                'job_id' => $job->getQueueId(),
                'job_type' => get_class($job),
            ];

            if ($reason) {
                $log_arguments['exception'] = $reason;
            }

            if (($previous_attempts + 1) >= $job->getAttempts()) {
                $log_arguments['event'] = 'job_failed';

                if ($this->log) {
                    $log_message = 'Job #{job_id} ({job_type}) failed after {attempts} attemtps';
                    $log_arguments['attempts'] = $previous_attempts + 1;

                    if ($reason instanceof Exception) {
                        $log_message .= '. Exception: {exception}';
                    }

                    $this->log->error($log_message, $log_arguments);
                }

                $this->logFailedJob($job, ($reason instanceof Exception ? $reason->getMessage() : ''));
            } else {
                $log_arguments['event'] = 'job_attempt_failed';

                if ($this->log) {
                    $log_message = 'Job #{job_id} ({job_type}) failed at attempt {attempt}';
                    $log_arguments['attempt'] = $previous_attempts + 1;

                    if ($reason instanceof Exception) {
                        $log_message .= '. Exception: {exception}';
                    }

                    $this->log->error($log_message, $log_arguments);
                }

                $this->prepareForNextAttempt($job_id, $previous_attempts, $job->getDelay());
            }
        }

        if (!empty($this->on_job_failure)) {
            foreach ($this->on_job_failure as $callback) {
                call_user_func($callback, $job, $reason);
            }
        }

        if ($reason instanceof Exception && !$silent) {
            throw $reason;
        }
    }
356062
protected function handleJobException($job, QueueMessage $message, Structure $options, $e)
    {
        if (!$job instanceof JobInterface) {
            $job = new NullJob();
        }

        $this->logger->error(
            sprintf(
                'Job [%s] (%s) failed: %s - Class: %s',
                $job->getName(),
                $message->getId(),
                $e->getMessage(),
                get_class($job)
            )
        );

        if (method_exists($job, 'failed')) {
            $job->failed($e);
        }

        $maxTries = (int) $options->get('tries', 5);

        // Delete and log error if reach max attempts.
        if ($maxTries !== 0 && $maxTries <= $message->getAttempts()) {
            $this->manager->delete($message);
            $this->logger->error(
                sprintf(
                    'Max attempts exceeded. Job: %s (%s) - Class: %s',
                    $job->getName(),
                    $message->getId(),
                    get_class($job)
                )
            );
        }

        $this->dispatcher->triggerEvent(
            'onWorkerJobFailure',
            [
                'worker' => $this,
                'exception' => $e,
                'job' => $job,
                'message' => $message,
            ]
        );
    }
664555
protected function save($successMessage, $failureMessage)
    {
        try {
            $this->getEntityManager()->flush();
            $this->addMessage($successMessage, FlashMessenger::NAMESPACE_SUCCESS);
            return true;
        } catch (\Exception $e) {
            $this->addMessage($failureMessage, FlashMessenger::NAMESPACE_ERROR);

            // Check exception type
            if ($e instanceof \Doctrine\DBAL\DBALException) {
                $previous = $e->getPrevious();
                if ($previous instanceof \Doctrine\DBAL\Driver\Mysqli\MysqliException) {

                    // Check exception type
                    switch ($previous->getCode()) {
                        case 1062:
                            $this->addMessage(
                                    'You are using details that already exist.', 'error'
                            );
                            return false;
                    }
                }
            }

            /**
             * TO BE REMOVED -- BELOW
             */
            throw new \Exception('You are seeing this because this error needs to be properly handled.', 0, $e);
            /**
             * TO BE REMOVED -- ABOVE
             */
            return false;
        }
    }
251184
protected function doJob(AbstractJob $job)
    {
        $this->validateJobParams($job);

        try {

            $response = $this->sendMail($job);
            $resultData['response'] = $response;

        } catch (\Exception $ex) {
            throw new ResultException(ResultException::RETRY_TRANSPORT_ERROR);
        }

        if(!$resultData['response']['success']){
            throw new ResultException(ResultException::R_FAILURE, $resultData);
        }

        throw new ResultException(ResultException::R_SUCCESS, $resultData);
    }
272706
protected function raiseFailedJobEvent($connection, Job $job)
    {
        if (isset($this->events)) {
            $this->events->dispatch('nova.queue.failed', array($connection, $job));
        }
    }
653012
public function logFailedJob(JobInterface $job, $reason)
    {
        if (mb_strlen($reason) > 191) {
            $reason = mb_substr($reason, 0, 191);
        }

        $this->connection->transact(function () use ($job, $reason) {
            $this->connection->execute('INSERT INTO `' . self::FAILED_JOBS_TABLE_NAME . '` (`type`, `channel`, `batch_id`, `data`, `failed_at`, `reason`) VALUES (?, ?, ?, ?, ?, ?)', get_class($job), $job->getChannel(), $job->getBatchId(), json_encode($job->getData()), date('Y-m-d H:i:s'), $reason);
            $this->deleteJob($job);
        });
    }
46089
public function handle(JobFailed $event)
    {
        $tags = collect($event->payload->tags())->map(function ($tag) {
            return 'failed:'.$tag;
        })->all();

        $this->tags->addTemporary(
            2880, $event->payload->id(), $tags
        );
    }