Using Laravel's rescue Helper for Elegant Exception Handling

This article explains Laravel's rescue helper function, demonstrates its basic usage and real‑world API integration examples, and shows how it provides a concise, robust way to handle exceptions without crashing the application.

php Courses
php Courses
php Courses
Using Laravel's rescue Helper for Elegant Exception Handling

Laravel's rescue helper function offers an elegant exception handling mechanism that prevents program crashes and keeps applications stable when errors occur.

Basic Usage

The following demonstrates how to use the rescue function:

// Simple usage
return rescue(function () {
    return $this->method();
});

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

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

Real‑World Example

Below is an actual implementation for API integration using rescue:

class ExternalServiceIntegration
{
    public function fetchUserData($userId)
    {
        return rescue(function () use ($userId) {
            $response = Http::get("api.example.com/users/{$userId}");
            return $response->json();
        }, [
            'id' => $userId,
            'status' => 'unavailable',
            'error' => '无法获取用户数据'
        ]);
    }

    public function syncProducts()
    {
        return rescue(
            function () {
                $products = $this->api->getProducts();
                foreach ($products as $product) {
                    $this->updateLocalProduct($product);
                }
                return true;
            },
            function () {
                Cache::put('sync_failed', true, now()->addHour());
                return false;
            },
            report: function (Throwable $e) {
                return !($e instanceof TemporaryException);
            }
        );
    }
}

// Using in a controller
class ProductController extends Controller
{
    public function index(ExternalServiceIntegration $service)
    {
        $synced = $service->syncProducts();
        return response()->json([
            'success' => $synced,
            'message' => $synced ? '产品同步成功' : '同步失败,使用缓存数据'
        ]);
    }
}

The rescue helper provides a concise way to handle potential errors, helping keep code clear and readable.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Exception HandlingPHPLaravelrescue
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.