HTTP Response throw() Makes Your Error Handling Unreachable

📖 1 minute read

Found dead code in an API client today. Classic mistake with Laravel’s HTTP client.

The code looked reasonable at first glance:

$response = Http::post($url, $data)->throw();

if ($response->failed()) {
    throw $response->serverError() 
        ? new ServerException() 
        : $response->toException();
}

Spot the problem? The throw() method already throws an exception if the request fails. That if ($response->failed()) block will never execute — it’s unreachable.

Laravel’s throw() is basically:

if ($this->failed()) {
    throw $this->toException();
}
return $this;

So you either use throw() for automatic exception handling, OR check failed() manually. Not both.

The fix: if you need custom exception logic, don’t use throw():

$response = Http::post($url, $data);

if ($response->failed()) {
    throw $response->serverError() 
        ? new CustomServerException() 
        : new CustomClientException();
}

Small mistake, but good reminder to understand what framework helpers actually do under the hood.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

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