Laravel Tutorials

Enhanced Queue Job Control with Laravel's ThrottlesExceptions failWhen() Method

Published
Enhanced Queue Job Control with Laravel's ThrottlesExceptions failWhen() Method image

Laravel's ThrottlesExceptions middleware recently gained a valuable enhancement with the introduction of the failWhen() method. This addition provides developers with precise control over job failure behavior, particularly beneficial for managing job chain execution flow.

The previous limitation with job exception handling centered around the binary choice between continuing execution and complete job deletion. The existing deleteWhen() method removes jobs entirely from the queue, which works well for certain scenarios but lacks nuance for complex workflows:

public function middleware(): array
{
return [
(new ThrottlesExceptions(2, 10 * 60))
->deleteWhen(CustomerNotFoundException::class)
];
}

The newly introduced failWhen() method bridges this gap by allowing jobs to be marked as failed while preserving failure information and stopping job chain execution:

public function middleware(): array
{
return [
(new ThrottlesExceptions(2, 10 * 60))
->deleteWhen(CustomerNotFoundException::class)
->failWhen(fn (\Throwable $e) => $e instanceof SystemCriticalException)
];
}

Consider an e-commerce inventory management system that processes product updates through chained jobs. When certain critical exceptions occur, you need the entire chain to halt rather than continue with potentially inconsistent data:

<?php
 
namespace App\Jobs;
 
use App\Exceptions\DatabaseConnectionException;
use App\Exceptions\InventoryLockedException;
use App\Exceptions\ProductDiscontinuedException;
use App\Exceptions\TemporaryNetworkException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\ThrottlesExceptions;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
 
class UpdateProductInventory implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
 
public $tries = 3;
 
public function __construct(
public Product $product,
public int $quantity
) {}
 
public function handle(InventoryService $service): void
{
Log::info('Updating product inventory', [
'product_id' => $this->product->id,
'quantity' => $this->quantity
]);
 
try {
$result = $service->updateStock($this->product, $this->quantity);
 
$this->product->update([
'stock_quantity' => $result->newQuantity,
'last_updated' => now()
]);
 
} catch (TemporaryNetworkException $e) {
Log::warning('Network issue during inventory update', [
'product_id' => $this->product->id,
'error' => $e->getMessage()
]);
throw $e;
 
} catch (DatabaseConnectionException $e) {
Log::critical('Database connection failed', [
'product_id' => $this->product->id,
'error' => $e->getMessage()
]);
throw $e;
 
} catch (InventoryLockedException $e) {
Log::error('Product inventory locked', [
'product_id' => $this->product->id,
'locked_until' => $e->getLockedUntil()
]);
throw $e;
}
}
 
public function middleware(): array
{
return [
(new ThrottlesExceptions(3, 5 * 60))
->deleteWhen(ProductDiscontinuedException::class)
->failWhen(function (\Throwable $e) {
return $e instanceof DatabaseConnectionException ||
$e instanceof InventoryLockedException ||
($e instanceof TemporaryNetworkException && $e->isPermanent());
})
->when(fn (\Throwable $e) => $e instanceof TemporaryNetworkException)
->report(function (\Throwable $e) {
return $e instanceof DatabaseConnectionException ||
$e instanceof InventoryLockedException;
})
];
}
 
public function failed(\Throwable $exception): void
{
Log::error('Product inventory update failed permanently', [
'product_id' => $this->product->id,
'exception' => $exception->getMessage(),
'chain_halted' => true
]);
 
$this->product->update([
'update_status' => 'failed',
'last_error' => $exception->getMessage()
]);
 
NotifyInventoryTeam::dispatch($this->product, $exception);
}
}
 
class InventoryController extends Controller
{
public function updateProductStock(Product $product, UpdateStockRequest $request)
{
Bus::chain([
new UpdateProductInventory($product, $request->quantity),
new RecalculateProductMetrics($product),
new UpdateSearchIndex($product),
new NotifyStockChange($product),
])->dispatch();
 
return response()->json([
'message' => 'Inventory update initiated',
'product_id' => $product->id
]);
}
}
 
class TemporaryNetworkException extends Exception
{
public function isPermanent(): bool
{
return str_contains($this->getMessage(), 'service permanently unavailable') ||
str_contains($this->getMessage(), 'endpoint deprecated');
}
}
 
class DatabaseConnectionException extends Exception {}
class InventoryLockedException extends Exception
{
public function getLockedUntil(): Carbon
{
return now()->addMinutes(30);
}
}
class ProductDiscontinuedException extends Exception {}

This implementation demonstrates the strategic use of both methods. The deleteWhen() method handles discontinued products that should be removed from processing entirely, while failWhen() manages critical system failures that require job chain termination and detailed failure tracking.

The fundamental distinction lies in their behavior:

  • deleteWhen(): Completely removes the job, allowing the chain to continue
  • failWhen(): Marks the job as failed, stops the chain, retains failure data for analysis

This approach provides comprehensive error handling with proper audit trails. Failed jobs remain accessible for debugging, and the failed() method enables custom failure recovery procedures while ensuring job chains halt appropriately.

The failWhen() method accepts both exception classes and closures, enabling sophisticated conditional logic for determining which exceptions should terminate job chain execution versus those that warrant retry attempts or deletion.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article