Laravel HTTP Client Retry Without Throwing an Exception
Leonel Elimpe
by Leonel Elimpe
~1 min read

Tags

  • Laravel

I used Laravel’s HTTP Client retry() feature for the first time yesterday and was surprised it throws an exception on failure of all retries instead of returning the failure Illuminate\Http\Client\Response object.

If you make a normal request like:

$response = Http::post(...);

You will always be returned an Illuminate\Http\Client\Response object, even if a server error or timeout occurs.

However, if you would like you request retried 3 times as below,

$response = Http::retry(3, 100)->post(...);

an exception will be thrown if the 3 attempts fail, or a timeout occurs. But I just want the response object returned, and after inspecting the exception thrown after the retries, I noticed the response object is attached to it. So I wrote this:

$response = rescue(function () {

    return Http::retry(3, 100)->post(...);

}, function ($e) {
    
    return $e->response;

});

With the above rescue() wrapper around the HTTP request, I always receive a response object and can safely go ahead to verify its status.

$response->successful() : bool;
$response->failed() : bool;
$response->serverError() : bool;
$response->clientError() : bool;

Hope this was helpful ;-).