Simplify HTTP Error Testing with Laravel's New requestException() Method

Laravel continues to improve developer experience with the addition of requestException(), a convenience method that streamlines creating HTTP client exceptions for testing.
When testing code that interacts with external APIs, you often need to simulate error responses to ensure your application handles failures gracefully. Previously, creating a RequestException for testing required verbose, multi-line code. The new requestException() method provides a cleaner, more concise alternative.
Let's see how it works:
use Illuminate\Support\Facades\Http;
// Create a request exception with a specific response body and status code
$exception = Http::requestException(['error' => 'not_found'], 404);
// Create a request exception with just a status code
$exception = Http::requestException(status: 500);
// Create a request exception with headers
$exception = Http::requestException(
['message' => 'Rate limited'],
429,
['X-RateLimit-Reset' => '60']
);
Before and After Comparison
The improvement in readability is substantial:
// Before: verbose, multi-step process
$exception = new RequestException(
new Response(
Http::response(['code' => 'not_found'], 404)->wait()
)
);
// After: clean, single-line approach
$exception = Http::requestException(['code' => 'not_found'], 404);
Real-World Example
This method is particularly useful when testing services that interact with external APIs:
class WeatherServiceTest extends TestCase
{
public function test_it_handles_api_not_found_errors()
{
Http::fake([
'api.weather.com/*' => Http::response(['error' => 'City not found'], 404),
]);
// Test the actual service handling of 404 errors
$service = new WeatherService();
$result = $service->getWeatherForCity('NonExistentCity');
$this->assertNull($result);
// Now test exception handling with a throw-catch approach
try {
// Mock the HTTP client to throw an exception
Http::fake(function () {
throw Http::requestException(['error' => 'City not found'], 404);
});
$service->getWeatherForCityOrFail('NonExistentCity');
$this->fail('Exception was not thrown');
} catch (CityNotFoundException $e) {
$this->assertEquals('NonExistentCity', $e->getCity());
$this->assertEquals(404, $e->getStatusCode());
}
}
}
By leveraging the new requestException() method, you can create cleaner, more maintainable tests for your HTTP interactions with less effort.
If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter (https://x.com/harrisrafto), Bluesky (https://bsky.app/profile/harrisrafto.eu), and YouTube (https://www.youtube.com/@harrisrafto). It helps a lot!