See rates for the top Laravel developers in Latin America

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
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Get expert guidance in a few days with a Laravel code review logo

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

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

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

PhpStorm

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

PhpStorm
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

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

Shift
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
Lucky Media logo

Lucky Media

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

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
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

The latest

View all →
Laravel Boost v1.8.10 Released With New AI Prompts and Livewire v4 Support image

Laravel Boost v1.8.10 Released With New AI Prompts and Livewire v4 Support

Read article
Statamic 6 Beta Now Available image

Statamic 6 Beta Now Available

Read article
Everything new in Livewire 4 image

Everything new in Livewire 4

Read article
Cache Without Overlapping in Laravel 12.47.0 image

Cache Without Overlapping in Laravel 12.47.0

Read article
Going Real-Time with Reverb - Laravel In Practice EP17 image

Going Real-Time with Reverb - Laravel In Practice EP17

Read article
PHP DebugBar v3 is released image

PHP DebugBar v3 is released

Read article