Improve HTTP Error Testing with Laravel's requestException() Method
Published on by Harris Raftopoulos

Laravel enhances developer testing capabilities with the addition of requestException(), a convenience method that simplifies creating HTTP client exceptions for more effective error testing.
Testing external API interactions requires simulating various error responses to verify proper exception handling. Previously, creating a RequestException involved verbose, multi-step code. The new requestException() method offers a concise, elegant alternative:
use Illuminate\Support\Facades\Http; // Create a request exception with a specific response body and status code$exception = Http::requestException(['error' => 'invalid_token'], 401); // Create a request exception with just a status code$exception = Http::requestException(status: 500); // Create a request exception with headers$exception = Http::requestException( ['message' => 'Too many requests'], 429, ['X-RateLimit-Reset' => '30']);
The readability improvement is significant:
// Before: verbose, multi-step process$exception = new RequestException( new Response( Http::response(['code' => 'invalid_token'], 401)->wait() )); // After: clean, single-line approach$exception = Http::requestException(['code' => 'invalid_token'], 401);
This method particularly enhances testing services that interact with external APIs:
class PaymentGatewayTest extends TestCase{ public function test_it_handles_api_authentication_errors() { Http::fake([ 'api.payment.com/*' => Http::response(['error' => 'Invalid API key'], 401), ]); // Test the service's handling of 401 errors $gateway = new PaymentGateway(); $result = $gateway->processPayment($paymentData); $this->assertFalse($result->success); $this->assertEquals('authentication_failed', $result->error); // Test exception handling with throw-catch approach try { // Mock the HTTP client to throw an exception Http::fake(function () { throw Http::requestException(['error' => 'Invalid API key'], 401); }); $gateway->processPaymentOrFail($paymentData); $this->fail('Exception was not thrown'); } catch (PaymentAuthenticationException $e) { $this->assertEquals(401, $e->getStatusCode()); $this->assertEquals('Invalid API key', $e->getErrorMessage()); } }}
The requestException() method creates cleaner, more maintainable tests for HTTP interaction error handling, enhancing code quality while reducing testing complexity.