Fine-Tuning HTTP Client Error Messages in Laravel

Fine-Tuning HTTP Client Error Messages in Laravel

Fine-tune your HTTP client error messages in Laravel with new exception truncation controls. These bootstrap configurations give you precise control over how request exceptions are displayed.

Basic Usage

Configure exception truncation in your bootstrap file:

// bootstrap/app.php
use Illuminate\Http\Client\RequestException;

return Application::configure(basePath: dirname(__DIR__))
    ->withExceptions(function (Exceptions $exceptions) {
        // Disable truncation completely
        $exceptions->dontTruncateRequestExceptions();
        
        // Or set custom length
        $exceptions->truncateRequestExceptionsAt(260);
    })->create();

Real-World Example

Here's how you might use it in a development environment:

// bootstrap/app.php
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\App;

return Application::configure(basePath: dirname(__DIR__))
    ->withExceptions(function (Exceptions $exceptions) {
        if (App::environment('local', 'testing')) {
            // Show full responses in development
            $exceptions->dontTruncateRequestExceptions();
        } else {
            // Limit response size in production
            $exceptions->truncateRequestExceptionsAt(500);
        }
        
        // Log full responses regardless of environment
        $exceptions->reportable(function (RequestException $e) {
            Log::error('API Request Failed', [
                'url' => $e->response->effectiveUri(),
                'status' => $e->response->status(),
                'full_response' => $e->response->body()
            ]);
        });
    })->create();

// In your service class
class ExternalApiService
{
    public function fetchData()
    {
        try {
            return Http::get('api.example.com/data');
        } catch (RequestException $e) {
            // Will show full or truncated response based on environment
            throw new ServiceException(
                "API request failed: {$e->getMessage()}"
            );
        }
    }
}

These configuration options help you balance between detailed debugging information and clean error outputs.

If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter and Bluesky. It helps a lot!

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe