error-explorer/laravel-error-reporter

Error reporting package for Laravel applications - automatically sends errors to Error Explorer monitoring platform

v1.0.0 2025-07-02 21:40 UTC

This package is auto-updated.

Last update: 2025-07-02 21:42:41 UTC


README

A Laravel package that automatically captures and reports exceptions to your Error Explorer monitoring platform.

Features

  • 🚀 Automatic Exception Capture: Listens to all unhandled exceptions in your Laravel application
  • 🔧 Zero Configuration: Works out of the box with minimal setup
  • 🛡️ Secure: Sanitizes sensitive data (passwords, tokens, etc.) before sending
  • Non-blocking: Asynchronous error reporting doesn't slow down your application
  • 🎯 Smart Filtering: Configurable exception filtering to ignore common framework exceptions
  • 📊 Rich Context: Captures request data, server info, stack traces, and more
  • 🔄 Wide Compatibility: Supports Laravel 8+ and PHP 7.4+ for maximum compatibility

Installation

Step 1: Install the Package

composer require error-explorer/laravel-error-reporter

Step 2: Publish Configuration (Optional)

The package works out of the box, but you can optionally publish the configuration file:

php artisan vendor:publish --tag=error-reporter-config

Step 3: Configure Environment Variables

Add these variables to your .env file:

# Error Explorer Configuration
ERROR_WEBHOOK_URL=https://your-error-explorer-domain.com
ERROR_WEBHOOK_TOKEN=your-unique-project-token
ERROR_PROJECT_NAME="My Laravel App"
ERROR_REPORTING_ENABLED=true

Configuration Options

Option Type Required Description
ERROR_WEBHOOK_URL string Yes The base URL of your Error Explorer instance
ERROR_WEBHOOK_TOKEN string Yes Unique project token from Error Explorer
ERROR_PROJECT_NAME string No Name identifier for your project (defaults to APP_NAME)
ERROR_REPORTING_ENABLED boolean No Enable/disable error reporting (default: true)

Default Ignored Exceptions

By default, these common Laravel exceptions are ignored:

  • Illuminate\Auth\AuthenticationException
  • Illuminate\Auth\Access\AuthorizationException
  • Illuminate\Database\Eloquent\ModelNotFoundException
  • Illuminate\Http\Exceptions\HttpResponseException
  • Illuminate\Http\Exceptions\ThrottleRequestsException
  • Illuminate\Session\TokenMismatchException
  • Illuminate\Validation\ValidationException
  • Symfony\Component\HttpKernel\Exception\HttpException
  • Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  • Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException

You can override this list in the published configuration file.

Usage

Automatic Error Reporting

Once configured, the package automatically captures and reports:

  • All unhandled exceptions
  • HTTP errors (4xx, 5xx)
  • Fatal errors and exceptions

Manual Error Reporting

Option 1: Using the Facade (Recommended)

use ErrorExplorer\LaravelErrorReporter\Facades\ErrorReporter;

class YourController extends Controller
{
    public function someAction()
    {
        try {
            // Your code here
        } catch (\Exception $e) {
            // Simple facade call
            ErrorReporter::reportError($e, 'production', 500);
            throw $e; // Re-throw if needed
        }
    }
}

Option 2: Using the Static Class

use ErrorExplorer\LaravelErrorReporter\ErrorReporter;

class YourController extends Controller
{
    public function someAction()
    {
        try {
            // Your code here
        } catch (\Exception $e) {
            // Static call
            ErrorReporter::reportError($e, 'production', 500);
            throw $e; // Re-throw if needed
        }
    }
}

Option 3: Service Injection

use ErrorExplorer\LaravelErrorReporter\Services\WebhookErrorReporter;

class YourController extends Controller
{
    public function __construct(
        private WebhookErrorReporter $errorReporter
    ) {}

    public function someAction()
    {
        try {
            // Your code here
        } catch (\Exception $e) {
            // Using injected service
            $this->errorReporter->reportError($e, 'production', 500);
            throw $e; // Re-throw if needed
        }
    }
}

Quick Helpers

use ErrorExplorer\LaravelErrorReporter\Facades\ErrorReporter;

// Simple report with defaults
ErrorReporter::report($exception);

// Report with context
ErrorReporter::reportWithContext($exception, 'staging', 404);

// Full control
ErrorReporter::reportError($exception, 'production', 500, $request);

Custom Messages & Events

Report Custom Messages

Report important events or custom messages without exceptions:

use ErrorExplorer\LaravelErrorReporter\Facades\ErrorReporter;

// Report a custom message
ErrorReporter::reportMessage('Payment processing failed for user 123', 'production', 500);

// Report with custom context
ErrorReporter::reportMessage(
    'Suspicious login attempt detected', 
    'production', 
    401, 
    null, 
    'warning', 
    ['user_id' => 123, 'ip' => '192.168.1.100']
);

Track Error Context with Breadcrumbs

Add breadcrumbs to track what led to an error. Best Practice: Only log critical steps that might fail, error conditions, or context needed for debugging - avoid logging successful operations:

💡 When to use breadcrumbs:

  • Before critical operations that might fail
  • When errors or warnings occur
  • For navigation paths leading to errors
  • To track slow or problematic operations

When NOT to use:

  • Successful operations
  • Normal business flow that works fine
  • Too granular steps that add noise
use ErrorExplorer\LaravelErrorReporter\Facades\ErrorReporter;

// Add breadcrumbs for critical steps that might fail
ErrorReporter::addBreadcrumb('User started checkout process', 'user', 'info', ['cart_items' => 3]);

// Log navigation to track user path to error
ErrorReporter::logNavigation('/cart', '/checkout');

// Log critical user actions that might cause issues
ErrorReporter::logUserAction('Attempting payment', ['product_id' => 456]);

// Log failed HTTP requests
ErrorReporter::logHttpRequest('POST', '/api/payment', 500, ['error' => 'timeout']);

// Log slow/problematic database queries
ErrorReporter::logQuery('SELECT * FROM users WHERE id = ?', 2500, ['user_id' => 123, 'slow_query' => true]);

// When an error occurs, all breadcrumbs provide context
try {
    // Some operation that might fail
} catch (\Exception $e) {
    ErrorReporter::reportError($e); // Includes all breadcrumbs for context
}

Real-World Example

use ErrorExplorer\LaravelErrorReporter\Facades\ErrorReporter;

class CheckoutController extends Controller
{
    public function processPayment($userId, $amount)
    {
        // Track critical step that might fail
        ErrorReporter::addBreadcrumb('Payment process initiated', 'payment', 'info', ['user_id' => $userId, 'amount' => $amount]);
        
        try {
            // Track critical steps (only potential failure points)
            ErrorReporter::addBreadcrumb('Validating user', 'validation');
            $user = $this->validateUser($userId);
            
            ErrorReporter::addBreadcrumb('Processing payment', 'payment', 'info', ['amount' => $amount]);
            $result = $this->paymentService->charge($user, $amount);
            
            // Success: no need to log, just return
            return $result;
            
        } catch (ValidationException $e) {
            // Report validation error with context
            ErrorReporter::reportMessage('User validation failed', 'production', 400, null, 'error', [
                'user_id' => $userId,
                'validation_errors' => $e->getErrors()
            ]);
            throw $e;
            
        } catch (PaymentException $e) {
            // Report payment error - breadcrumbs are included automatically
            ErrorReporter::reportError($e, 'production', 402);
            throw $e;
        }
    }
}

Data Captured

The package captures comprehensive error context:

Exception Data

  • Exception message and class
  • Stack trace
  • File and line number
  • HTTP status code (when applicable)

Request Context

  • URL and HTTP method
  • Route name
  • Client IP and User-Agent
  • Request parameters (sanitized)
  • Query parameters (sanitized)
  • Headers (sensitive ones redacted)

Server Context

  • PHP version
  • Laravel version
  • Memory usage (current and peak)
  • Environment (local/staging/production)
  • Timestamp

Breadcrumbs & User Journey

  • User actions and navigation
  • HTTP requests and responses
  • Database queries with timing
  • Custom events and markers
  • Automatic chronological ordering
  • Maximum 50 breadcrumbs (configurable)

Security Features

Sensitive data is automatically sanitized:

  • Parameters: password, token, secret, key, api_key, authorization, password_confirmation
  • Headers: authorization, cookie, x-api-key, x-auth-token

Sensitive values are replaced with [REDACTED].

Error Fingerprinting

Errors are automatically grouped using a fingerprint based on:

  • Exception class
  • File path
  • Line number

This allows Error Explorer to group similar errors together.

Compatibility

PHP & Laravel Support

Component Minimum Version Recommended
PHP 7.4+ 8.1+
Laravel 8.0+ 10.0+

Supported Laravel Versions

  • ✅ Laravel 8.x
  • ✅ Laravel 9.x
  • ✅ Laravel 10.x
  • ✅ Laravel 11.x

Compatibility Matrix

PHP Version Laravel 8.x Laravel 9.x Laravel 10.x Laravel 11.x
7.4
8.0
8.1
8.2
8.3+

The package automatically adapts to your PHP and Laravel version for maximum compatibility.

Development vs Production

Development Environment

# .env.local
ERROR_REPORTING_ENABLED=false  # Disable in development

Production Environment

# .env
ERROR_REPORTING_ENABLED=true
ERROR_WEBHOOK_URL=https://errors.yourcompany.com
ERROR_WEBHOOK_TOKEN=prod-token-xyz
ERROR_PROJECT_NAME="My App Production"

Troubleshooting

Package Not Capturing Errors

  1. Check that ERROR_REPORTING_ENABLED=true
  2. Verify your webhook URL and token are correct
  3. Check Laravel logs for any HTTP client errors
  4. Ensure the exception is not in the ignored list

HTTP Client Errors

The package silently fails if the webhook is unreachable. Check your logs:

php artisan log:search "Failed to report error"

Testing the Integration

Create a test route to verify the integration:

// routes/web.php
Route::get('/test-error-reporting', function () {
    throw new \Exception('Test error for Error Explorer');
});

Service Provider Issues

If the service provider is not auto-discovered, manually register it in config/app.php:

'providers' => [
    // ... other providers
    ErrorExplorer\LaravelErrorReporter\ErrorReporterServiceProvider::class,
],

'aliases' => [
    // ... other aliases
    'ErrorReporter' => ErrorExplorer\LaravelErrorReporter\Facades\ErrorReporter::class,
],

Advanced Configuration

Custom Exception Handler

If you have a custom exception handler, you can manually integrate Error Explorer:

// app/Exceptions/Handler.php
use ErrorExplorer\LaravelErrorReporter\Facades\ErrorReporter;

class Handler extends ExceptionHandler
{
    public function report(Throwable $exception)
    {
        // Report to Error Explorer
        if (app()->bound('error-reporter-service')) {
            ErrorReporter::reportError($exception);
        }
        
        parent::report($exception);
    }
}

Custom Ignored Exceptions

Customize which exceptions to ignore:

// config/error-reporter.php
'ignore_exceptions' => [
    // Add your custom exceptions here
    App\Exceptions\CustomIgnoredException::class,
    // Remove default ones you want to track
    // \Illuminate\Validation\ValidationException::class, // Now this will be reported
],

Performance Considerations

  • Error reporting is asynchronous and doesn't block your application
  • HTTP timeout is set to 5 seconds by default
  • Breadcrumbs are stored in memory (cleared after each request)
  • Sensitive data sanitization has minimal performance impact

License

MIT License

Support

For issues and questions:

  1. Check the Error Explorer documentation
  2. Review this README
  3. Check your Error Explorer dashboard for received errors
  4. Verify your configuration and environment variables