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

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Migration Durations and Job Memory Usage in Laravel 13.45 image

Migration Durations and Job Memory Usage in Laravel 13.45

Read article
Laravel CLI: One Binary for New PHP and Rust Laravel Apps image

Laravel CLI: One Binary for New PHP and Rust Laravel Apps

Read article
Phactorial: Render LaTeX Math to SVG and PNG in PHP image

Phactorial: Render LaTeX Math to SVG and PNG in PHP

Read article
Laravel, reimagined image

Laravel, reimagined

Read article
Laravel Rust: A New Rust Web Framework From Laravel image

Laravel Rust: A New Rust Web Framework From Laravel

Read article
Laravel Converse and Agent Kit for Chat Bots and AI Agents image

Laravel Converse and Agent Kit for Chat Bots and AI Agents

Read article