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

Defines FriendlyExceptionInterface for exceptions that provide a human-friendly name and suggested solution. Lets error handlers detect these exceptions and display clearer, actionable information on error pages. Includes guidance for writing short, markdown-based solutions.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require yiisoft/friendly-exception:^1.2
    

    Ensure your project meets the PHP 7.4+ requirement (now enforced in 1.2.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 (PHP 7.4+ syntax highlighting)
    • Environment details (PHP version, Laravel version)

Implementation Patterns

Core Workflows

  1. Environment-Specific Rendering Use ExceptionHandler with environment checks (PHP 7.4+ features supported):

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

    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 (PHP 7.4+ arrow functions supported):

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

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

Common Patterns

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

Gotchas and Tips

Pitfalls

  1. PHP Version Compatibility

    • Gotcha: Projects using PHP <7.4 will fail installation. Fix: Update PHP version or pin to yiisoft/friendly-exception:^1.1 in composer.json.
    • Tip: Verify compatibility with:
      composer validate --strict
      
  2. 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 (PHP 7.4+ env() helper):
      $handler = new ExceptionHandler(['debug' => (bool) env('APP_DEBUG')]);
      
  3. Stack Trace Truncation

    • Gotcha: Long stack traces may break layouts. Fix: Limit trace depth in config (PHP 7.4+ array destructuring):
      $handler = new ExceptionHandler(['maxStackTraceLines' => 20]);
      

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 (PHP 7.4+ return type hints):
    $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 (PHP 7.4+ union types):

    $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 (PHP 7.4+ named arguments):

    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 (PHP 7.4+ JSON_THROW_ON_ERROR):

    $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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope