Use throw(), throwIf(), and throwUnless() on Laravel HTTP client responses to handle 4xx and 5xx API errors with standard exception workflows.
By default, Laravel's Http client does not throw exceptions when receiving 4xx or 5xx HTTP response codes. Calling $response->json() on a 404 or 500 response returns the error body rather than failing.
Using ->throw() forces the client to throw an Illuminate\Http\Client\RequestException on error responses.
Basic Usage
use Illuminate\Support\Facades\Http;
// Throws RequestException automatically if status code is >= 400
$data = Http::get('https://api.example.com/user/profile')
->throw()
->json();
Conditional Exceptions with throwIf()
Throw exceptions only under specific business conditions:
$response = Http::post('https://api.example.com/order', $payload);
// Throws exception if response status is 422 or if custom error key exists
$response->throwIf(function ($response) {
return $response->status() === 422 || $response->json('has_error') === true;
});
Custom Error Callbacks
Inspect error details before throwing:
$response = Http::get('https://api.example.com/data')
->throw(function ($response, $exception) {
logger()->error('API request failed: ' . $response->body());
});
Summary
throw()converts 4xx and 5xx responses into catchableRequestExceptioninstances.- Access response details via
$exception->response->status()and$exception->response->body(). - Keeps API integration code clean and compatible with standard
try-catchblocks.
Related Tips
View all tips →Handle Hybrid API and Web Controllers with $request->expectsJson()
Use $request->expectsJson() in hybrid controllers to serve formatted JSON responses to API/AJAX requests and redirects to standard web browsers.
Authenticate External API Requests Cleanly with withToken()
Use withToken() on the Laravel HTTP client to attach Authorization Bearer tokens without manual header string formatting.