The rescue() Helper
Execute a closure and swallow any exceptions, optionally returning a fallback value — a try/catch in a single expression.
Overview
rescue() wraps a closure in a try/catch. If the closure throws, it returns a fallback value (or null) instead of crashing. The exception is reported to your exception handler by default.
Usage
// Returns null if the API call fails
$price = rescue(fn () => $this->fetchExternalPrice($sku));
// Returns a fallback value on failure
$rate = rescue(
fn () => Http::get('https://api.rates.com/usd')->json('rate'),
1.00,
);
The fallback can also be a closure:
$avatar = rescue(
fn () => $this->downloadAvatar($user),
fn () => $this->defaultAvatar(),
);
To suppress reporting, pass false as the third argument:
$value = rescue(fn () => riskyOperation(), 'default', report: false);
When to Use
- Calling external APIs where failures are expected and recoverable
- Fetching optional data that shouldn't break the main flow
- Graceful degradation for non-critical features