Laravel Tutorials

Handling Exceptions with Laravel's rescue Helper

Published
Handling Exceptions with Laravel's rescue Helper image

Laravel's rescue function provides an elegant approach to managing potential exceptions in your code, allowing operations to continue gracefully even when errors occur.

The function accepts several parameters for flexible implementation:

// Execute code with default null fallback
return rescue(function () {
    return $this->method();
});

// Specify a default value
return rescue(function () {
    return $this->method();
}, false);

// Use a fallback closure
return rescue(function () {
    return $this->method();
}, function () {
    return $this->fallbackMethod();
});

This approach proves particularly valuable when working with external services:

class ApiService
{
    public function fetchAccountData($accountId)
    {
        return rescue(function () use ($accountId) {
            $response = Http::timeout(3)->get("api.external.com/accounts/{$accountId}");
            $response->throw();
            return $response->json();
        }, [
            'id' => $accountId,
            'name' => 'Unknown',
            'status' => 'error',
            'last_checked' => now()
        ]);
    }
    
    public function processReports()
    {
        return rescue(
            function () {
                $reports = $this->getReports();
                $processed = [];
                
                foreach ($reports as $report) {
                    $processed[] = $this->processReport($report);
                }
                
                return $processed;
            },
            function () {
                Log::warning('Report processing failed, using cached data');
                return Cache::get('last_successful_reports', []);
            }
        );
    }
}

The rescue function enhances code reliability by providing built-in error recovery mechanisms without complicating your application's logic with extensive try-catch blocks.

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 →
Migration Durations and Job Memory Usage in Laravel 13.45 image

Migration Durations and Job Memory Usage in Laravel 13.45

Read article
Laravel CLI: One Binary for New PHP and Rust Laravel Apps image

Laravel CLI: One Binary for New PHP and Rust Laravel Apps

Read article
Phactorial: Render LaTeX Math to SVG and PNG in PHP image

Phactorial: Render LaTeX Math to SVG and PNG in PHP

Read article
Laravel, reimagined image

Laravel, reimagined

Read article
Laravel Rust: A New Rust Web Framework From Laravel image

Laravel Rust: A New Rust Web Framework From Laravel

Read article
Laravel Converse and Agent Kit for Chat Bots and AI Agents image

Laravel Converse and Agent Kit for Chat Bots and AI Agents

Read article