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

Friendly Exception Laravel Package

yiisoft/friendly-exception

User-friendly exception handling for PHP apps: convert throwables into readable messages, safe debug views, and structured data for logs/HTTP responses. Helps present errors clearly in production while keeping rich context for developers.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require yiisoft/friendly-exception
    

    Add to composer.json if using Yii:

    "yiisoft/friendly-exception": "^1.0"
    
  2. Basic Usage For Laravel, register the exception handler in app/Exceptions/Handler.php:

    use Yiisoft\FriendlyException\ExceptionHandler;
    
    public function register()
    {
        $this->renderable(function (Throwable $e) {
            return (new ExceptionHandler())->handle($e);
        });
    }
    
  3. First Use Case Trigger an exception in a route:

    Route::get('/test-error', function () {
        throw new \RuntimeException('Test error for debugging');
    });
    

    Visit /test-error to see a formatted error page with:

    • Exception message
    • Stack trace with file/line context
    • Environment details (PHP version, Laravel version)

Implementation Patterns

Core Workflows

  1. Environment-Specific Rendering Use ExceptionHandler with environment checks:

    $handler = new ExceptionHandler();
    if (app()->environment('local')) {
        $handler->setDebugMode(true);
    }
    
  2. Custom Error Pages Extend Renderer to modify output:

    use Yiisoft\FriendlyException\Renderer\Renderer;
    
    class CustomRenderer extends Renderer
    {
        protected function renderException(Throwable $exception): string
        {
            return "<div class='custom-error'>" . parent::renderException($exception) . "</div>";
        }
    }
    
  3. Integration with Laravel’s Exception Handler Override render() in Handler.php:

    public function render($request, Throwable $exception)
    {
        return (new ExceptionHandler())->handle($exception);
    }
    
  4. Logging Exceptions Combine with Laravel’s logging:

    $handler = new ExceptionHandler();
    $handler->setLogger(\Log::channel('single'));
    

Common Patterns

  • Stack Trace Highlighting: Use StackTraceRenderer for syntax-highlighted code snippets.
  • Environment Variables: Pass APP_ENV to control verbosity:
    $handler = new ExceptionHandler(['debug' => app()->isLocal()]);
    
  • Middleware for Debugging: Create middleware to wrap exceptions:
    class DebugExceptionMiddleware
    {
        public function handle($request, Closure $next)
        {
            try {
                return $next($request);
            } catch (Throwable $e) {
                return (new ExceptionHandler())->handle($e);
            }
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Production Safety

    • Gotcha: Forgetting to disable debug mode in production. Fix: Always set debug: false in non-local environments:
      $handler = new ExceptionHandler(['debug' => false]);
      
    • Tip: Use APP_DEBUG env var:
      $handler = new ExceptionHandler(['debug' => (bool) env('APP_DEBUG')]);
      
  2. Stack Trace Truncation

    • Gotcha: Long stack traces may break layouts. Fix: Limit trace depth in config:
      $handler = new ExceptionHandler(['maxStackTraceLines' => 20]);
      
  3. Yii Integration Conflicts

    • Gotcha: Yii’s ErrorHandler may override Laravel’s exception handling. Fix: Disable Yii’s handler if using Laravel:
      Yii::$container->set(ErrorHandler::class, new class extends ErrorHandler {
          public function handleException($exception): void { /* Custom logic */ }
      });
      

Debugging Tips

  • Disable Caching: Clear Laravel’s view cache if errors render incorrectly:
    php artisan view:clear
    
  • Inspect Renderer: Use dd() on the renderer to debug output:
    $renderer = new Renderer();
    dd($renderer->renderException($exception));
    
  • Custom Error Views: Override Laravel’s errors views in resources/views to embed friendly-exception output.

Extension Points

  1. Add Context Data Attach custom data to exceptions:

    $exception = new \RuntimeException('Failed', 0, null);
    $exception->setContext(['user_id' => auth()->id()]);
    

    Render it in a custom renderer:

    $context = $exception->getContext();
    echo "<pre>User ID: {$context['user_id']}</pre>";
    
  2. Plugin System Extend Renderer to add tabs or sections:

    class PluginRenderer extends Renderer
    {
        protected function renderTabs(Throwable $exception): string
        {
            return '<div class="plugin-tab">Custom Data</div>';
        }
    }
    
  3. API Error Responses Return JSON for APIs:

    $handler = new ExceptionHandler(['format' => 'json']);
    return response()->json($handler->handle($exception));
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport