Tips 01/01/2026 2 min read

Clean Up Your Try-Catch Blocks with the Rescue Helper

B
Beartropy Team
hace 1 día

In Laravel development, we often find ourselves wrapping risky operations—like external API calls or database transactions—in verbose try-catch blocks just to return a default value on failure.

While functional, this adds visual noise to your controllers and services. Enter the rescue() helper.

The Traditional Approach

Typically, you might write code that looks like this:

1try {
2 $response = Http::get('[https://external-api.com/users](https://external-api.com/users)');
3 return $response->json();
4} catch (\Exception $e) {
5 // Log the error manually if needed
6 Log::error($e->getMessage());
7 
8 // Return a default value
9 return [];
10}

The rescue() Approach

Laravel provides the rescue global helper, which executes a closure and catches any exceptions that occur. If an exception is thrown, it returns the second argument (the default value).

Here is the same logic refactored:

1return rescue(function () {
2 return Http::get('[https://external-api.com/users')-](https://external-api.com/users')-)>json();
3}, [], 'The external API failed');

How it works

  1. First Argument: The closure to execute.
  2. Second Argument: The value to return on failure (optional, defaults to null).
  3. Third Argument: Whether to report the exception to the error handler (e.g., Sentry or Flare). You can pass true or a custom boolean logic.

When to use it?

This helper is perfect for scenarios where an error is expected or acceptable, and you want to ensure the application flow continues gracefully without cluttering your code logic.

Start using rescue() today to make your code more readable and expressive!

Tags

#laravel #clean-code #refactoring #helpers

Share this post