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

Published on by

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

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell

The latest

View all →
LaraOwl: Self-Hosted Monitoring for Laravel Applications image

LaraOwl: Self-Hosted Monitoring for Laravel Applications

Read article
Filament Storage Monitor: Track Disk Usage From Your Filament Dashboard image

Filament Storage Monitor: Track Disk Usage From Your Filament Dashboard

Read article
Subscriptionify: Feature-Based Subscription Management for Laravel image

Subscriptionify: Feature-Based Subscription Management for Laravel

Read article
Toolkit: Reusable AI Tools for the Laravel AI SDK image

Toolkit: Reusable AI Tools for the Laravel AI SDK

Read article
Laracon US 2026 Reveals Its Full Speaker Lineup image

Laracon US 2026 Reveals Its Full Speaker Lineup

Read article
The State of PHP 2026 Survey Is Now Open image

The State of PHP 2026 Survey Is Now Open

Read article