Laravel Tutorials

Improve HTTP Error Testing with Laravel's requestException() Method

Published
Improve HTTP Error Testing with Laravel's requestException() Method image

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.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
UUID Request Input and Migration Failure Events in Laravel 13.42 image

UUID Request Input and Migration Failure Events in Laravel 13.42

Read article
Replay Missed Laravel Scheduled Tasks With Schedule Catchup image

Replay Missed Laravel Scheduled Tasks With Schedule Catchup

Read article
Search Polymorphic Relations and Filament Tables With Laravel Searchable image

Search Polymorphic Relations and Filament Tables With Laravel Searchable

Read article
Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs image

Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs

Read article
Real-Time Inertia Props With Laravel Reverb image

Real-Time Inertia Props With Laravel Reverb

Read article
PhpStorm 2026.3 Adds an Agent Workspace and PHP 8.6 Support image

PhpStorm 2026.3 Adds an Agent Workspace and PHP 8.6 Support

Read article