I have a background job that updates data via models. The issue is that when one of the job fails due to errors/exceptions (even when try/catch is used as long as an exception occurred), the rest of the other queued jobs which are successful do not update data even when there are no more errors.
When re-running the queued jobs; removing specifically those that contain errors beforehand, they successfully update data. Which means, that data update for all jobs does not work if at least one job fails.
Below is the code on my job that does the processing
public function handle()
{
try {
(new BenefitSyncController())->execute($this->sync_id);
} catch (\Exception $exception) {
$this->fail($exception);
}
}
public function fail($exception = null)
{
if ($exception != null) {
$sync = BenefitSync::where('id', $this->sync_id)->first();
$sync->errors = json_encode([
'message' => $exception->getMessage(),
'stacktrace' => $exception->getTraceAsString(),
]);
$sync->status = BenefitSyncStatus::FAILED;
$sync->attempts += 1;
$sync->save();
}
}
I've added a failed job handler, but this also doesn't work even when it's triggered. It seems like that when an exception happens, any model/database update will not push through.
Is there any way to get around this? For additional context, the queue driver is database, not sync. Altho I've tried sync, and it's pretty much the same.
Additional findings:
For anyone who experiences the same issue, apparently, the data does go in and is being reverted as previously stated on the new findings when I edited the question above.
All I had to do was replace the DB::beginTransaction
and DB::commit()
with DB::transaction(function()...)
basically wrapping the code that processes/updates the data inside the transaction function instead of being between the beginTransaction and commit, which altho is pretty much the same; this one actually works as intended.
Idk why it wasn't working properly with just the beginTransaction and commit, but this solves the issue. Even when one of the jobs fail, the others are not affected/rolled-back anymore.