Use rescue() to Prevent Small Failures from Breaking Your Laravel App
🚀 The Real Problem
In real projects, we often call code that might fail:
- External API calls
- File operations
- Optional database records
- Third-party packages
Usually, we write this:
try {
$data = riskyOperation();
} catch (\Exception $e) {
$data = null;
}
It works — but it’s repetitive and ugly.
Laravel gives you a cleaner solution.
🎯 The Laravel Way: rescue()
$data = rescue(fn () => riskyOperation());
That’s it.
If an exception occurs:
- Laravel catches it
- Returns
nullinstead of crashing
🧠 Real-World Example: External API Call
$response = rescue(function () {
return Http::get('https://api.example.com/data')->json();
});
If the API:
- is down
- times out
- returns an error
Your app does not break.
🛒 Example: Optional File Read
$config = rescue(fn () => file_get_contents(storage_path('config.json')));
No file?
No crash.
Just null.
🏁 Final Thought
rescue() is perfect when:
- failure is acceptable
- data is optional
- you don’t want the app to crash
- you want clean, readable code
It replaces multiple try–catch blocks with one expressive helper.