Currently Available: Need a skilled Software Developer for your next project?
Categories
Laravel

Handling HTTP Client Failures with ThrowIf and Retry

When Laravel code calls an external API, the server can return an HTTP error status (4xx or 5xx), or the request can fail before Laravel receives a response, as with a connection timeout. Laravel’s HTTP client returns 4xx and 5xx responses without throwing an exception automatically. The code that makes the request chooses what to do next: inspect the response, use throwIf to turn it into an exception, or use retry to make another attempt.

Use throwIf to decide how to handle a response Laravel has already received. Use retry to repeat a request when a failure meets the integration’s rules for retrying. Those choices solve different problems, and a request can use both: retry selected failures, then handle the final response.

Decide what counts as an exceptional response

An HTTP status code of 4xx or 5xx still arrives as a response, so code can inspect its status and body. Laravel provides methods such as failed(), clientError(), and serverError() for checking the result. When a timeout or other connection failure prevents Laravel from receiving an ordinary response, Laravel raises a ConnectionException. The Laravel HTTP client documentation describes both response checks and exception handling.

Call throwIf after the request when a failed response should stop normal processing. Its condition can be a boolean or a callback that receives the response. For example, this code throws only for server errors:

use Illuminate\Http\Client\Response;

$response = Http::get($url);

$response->throwIf(
    fn (Response $response) => $response->serverError()
);

The method throws a RequestException when the response failed and the condition matched. If the condition does not match, the response remains available for further handling. That makes throwIf useful when the integration treats some statuses as expected outcomes. For example, code might handle a not-found response as “record not found” while treating a 5xx response as an exceptional failure. Laravel’s response implementation shows how throwIf evaluates the response.

Retry only failures the integration can recover from

Before sending the pending request, call retry when the integration should make another attempt. Laravel lets the request specify an attempt limit and a delay in milliseconds. A callback can narrow retries to particular failures, such as connection exceptions or server-error responses. The retry documentation also describes callbacks that adjust the request before another attempt, such as refreshing an authorization token.

The code below retries connection failures and server-error responses. After the attempts, Laravel returns the last HTTP response, and throwIf throws if that response still indicates failure:

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use Throwable;

$response = Http::retry(
    3,
    100,
    function (Throwable $exception, PendingRequest $request): bool {
        return $exception instanceof ConnectionException
            || (
                $exception instanceof RequestException
                && $exception->response->serverError()
            );
    },
    throw: false,
)->get($url);

$response->throwIf(
    fn (Response $response) => $response->failed()
);

With throw: false, Laravel returns the last response when retries end with an HTTP failure, but it still throws a ConnectionException if every attempt fails at the connection level. The callback signature and available options can vary by Laravel version, so check the documentation for the version installed in the project. Laravel 11’s retry examples show version-specific callback and delay patterns.

Without throw: false, Laravel throws a RequestException by default when retries end with a failed response. Choose that default when the caller should handle an exhausted HTTP failure as an exception. Return the last response when the caller needs to branch on its status or body. In either case, catch exceptions where your code can respond to the failure, whether by logging or reporting it or by turning it into an application-level result.

Check whether repeating the request is safe

A retry sends the request again. For a read request, another attempt may be a reasonable response to a temporary connection problem or server error. When a request creates or changes remote data, the provider may receive the first attempt even if Laravel never receives a response. Sending the request again could repeat the remote action.

Before retrying a write, check the provider’s rules for duplicate requests and whether it supports an idempotency key, a value that lets the provider recognize repeated submissions of the same operation. Laravel’s retry feature does not guarantee that a provider will prevent duplicate effects. Keep the attempt limit and delay aligned with the integration’s latency needs, and avoid retrying every 4xx or 5xx response without a reason to expect another attempt to help.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *