Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Error Handler Laravel Package

symfony/error-handler

Symfony ErrorHandler provides robust error and exception handling tools for PHP. Enable debug mode, register an error handler, and use DebugClassLoader for better stack traces. Convert PHP notices/warnings into exceptions and wrap risky code with ErrorHandler::call for safer debugging.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require symfony/error-handler
    
  2. Enable debug mode (for development):
    use Symfony\Component\ErrorHandler\Debug;
    Debug::enable();
    
  3. First use case: Wrap risky operations to ensure exceptions are thrown:
    $data = \Symfony\Component\ErrorHandler\ErrorHandler::call(function () {
        return json_decode(file_get_contents('data.json'));
    });
    

Key Starting Points

  • For Laravel developers: Use in AppServiceProvider or bootstrap/app.php to enable globally.
  • For CLI scripts: Register handlers early in artisan commands:
    use Symfony\Component\ErrorHandler\ErrorHandler;
    ErrorHandler::register();
    

Implementation Patterns

Core Workflows

1. Unified Error Handling

Replace Laravel’s @ operator or try-catch blocks with ErrorHandler::call():

// Before: Silenced errors (risky)
$fileContent = @file_get_contents('config.json');

// After: Exceptions for all errors
$data = ErrorHandler::call(function () {
    return file_get_contents('config.json');
});

2. Debug Mode Integration

Enable in AppServiceProvider:

public function boot()
{
    if (app()->environment('local')) {
        Debug::enable();
    }
}

3. Custom Error Templates

Override default error pages (e.g., for APIs):

use Symfony\Component\ErrorHandler\HtmlErrorRenderer;
HtmlErrorRenderer::setTemplate(__DIR__.'/custom-error-template.html.php');

4. Production Error Redaction

Sanitize sensitive data in stack traces:

use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer;
HtmlErrorRenderer::setTemplate(__DIR__.'/production-error-template.html.php');
// Template masks API keys, passwords, etc.

5. Queue Job Error Handling

Wrap queue jobs to ensure failures propagate:

use Illuminate\Bus\Queueable;
use Symfony\Component\ErrorHandler\ErrorHandler;

class ProcessPayment implements Queueable
{
    public function handle()
    {
        return ErrorHandler::call(function () {
            // Payment logic here
        });
    }
}

6. Debugging Autoloading Issues

Enable DebugClassLoader for class resolution problems:

use Symfony\Component\ErrorHandler\DebugClassLoader;
DebugClassLoader::enable();

Laravel-Specific Patterns

Middleware for Error Standardization

Create middleware to wrap requests:

namespace App\Http\Middleware;

use Closure;
use Symfony\Component\ErrorHandler\ErrorHandler;

class StandardizeErrors
{
    public function handle($request, Closure $next)
    {
        return ErrorHandler::call(function () use ($request, $next) {
            return $next($request);
        });
    }
}

API Error Responses

Convert exceptions to JSON responses:

use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\HttpFoundation\JsonResponse;

public function handle(Exception $e)
{
    $flattened = FlattenException::createFromThrowable($e);
    return new JsonResponse([
        'error' => $flattened->getMessage(),
        'trace' => $flattened->getTraceAsString(),
    ], 500);
}

Testing with ErrorHandler

Force exceptions in tests:

public function testPaymentFailure()
{
    $this->expectException(\RuntimeException::class);
    ErrorHandler::call(function () {
        // Simulate a failed payment
    });
}

Gotchas and Tips

Pitfalls

  1. Debug Mode in Production

    • Gotcha: Forgetting to disable Debug::enable() in production can expose sensitive data.
    • Fix: Use environment checks:
      if (app()->environment('local')) {
          Debug::enable();
      }
      
  2. Silenced Errors Still Matter

    • Gotcha: Using @ or ErrorHandler::call() doesn’t mean errors are ignored—ensure they’re logged.
    • Fix: Pair with Laravel’s logging:
      ErrorHandler::call(function () {
          // Risky code
      }, function ($error) {
          \Log::error($error);
      });
      
  3. Custom Templates Override

    • Gotcha: Setting a custom template globally affects all errors.
    • Fix: Use context-specific templates or conditionally set them.
  4. Performance Overhead

    • Gotcha: ErrorHandler::call() adds minor overhead to every wrapped block.
    • Fix: Reserve for critical paths only (e.g., payments, file I/O).
  5. Deprecation Warnings

    • Gotcha: Some deprecation warnings (e.g., PHPUnit stubs) may be suppressed.
    • Fix: Explicitly enable deprecation handling:
      ErrorHandler::register(null, true); // Enable deprecation notices
      

Debugging Tips

  1. Inspect Flattened Exceptions Use FlattenException to debug:

    $flattened = FlattenException::createFromThrowable($e);
    dump($flattened->getMessage(), $flattened->getTrace());
    
  2. Enable Verbose Error Output For CLI debugging:

    Debug::enable(true); // Enable verbose mode
    
  3. Log Unhandled Errors Catch and log errors globally:

    ErrorHandler::register(function ($error) {
        \Log::critical($error, ['exception' => $error]);
    });
    
  4. Debug Autoloading Issues Use DebugClassLoader to trace class resolution:

    DebugClassLoader::enable();
    // Trigger an error in a missing class to see autoloading details
    
  5. Custom Error Renderers Extend HtmlErrorRenderer for tailored output:

    class CustomErrorRenderer extends HtmlErrorRenderer
    {
        protected function renderException(ExceptionInterface $exception): string
        {
            // Custom logic
        }
    }
    

Extension Points

  1. Custom Error Handlers Override default behavior:

    ErrorHandler::register(function ($error) {
        // Custom logic (e.g., send to Sentry, Slack)
    });
    
  2. Integrate with Laravel Events Dispatch events on errors:

    ErrorHandler::register(function ($error) {
        event(new \App\Events\ErrorOccurred($error));
    });
    
  3. Conditional Error Handling Route errors based on context:

    ErrorHandler::call(function () {
        // API logic
    }, function ($error) {
        if (app()->bound('http.request')) {
            // Return JSON error
        } else {
            // Log and rethrow
        }
    });
    
  4. Dynamic Template Selection Use middleware to set templates per route:

    public function handle($request, Closure $next)
    {
        if ($request->is('api/*')) {
            HtmlErrorRenderer::setTemplate(__DIR__.'/api-error-template.html.php');
        }
        return $next($request);
    }
    
  5. Error Metrics Track error rates with Prometheus:

    ErrorHandler::register(function () {
        \Prometheus\CollectorRegistry::default()->getOrRegisterCounter(
            'app_errors_total',
            'Total errors',
            ['type']
        )->inc();
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata