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

Laravel Exceptions Laravel Package

jftecnologia/laravel-exceptions

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require jftecnologia/laravel-exceptions
    php artisan vendor:publish --provider="Jftecnologia\LaravelExceptions\LaravelExceptionsServiceProvider" --tag="config"
    php artisan migrate
    
    • Publishes config (config/exceptions.php) and creates the database table for exception logging.
  2. First Use Case: Throw a custom exception in a controller or service:

    use Jftecnologia\LaravelExceptions\Exceptions\CustomException;
    
    throw new CustomException('User not found', 'Usuário não encontrado');
    
    • The first argument is the developer message, the second is the user-friendly message (supports i18n).
  3. View Exceptions:

    • Logs are stored in exceptions table. Query via Eloquent:
      use Jftecnologia\LaravelExceptions\Models\ExceptionLog;
      
      $logs = ExceptionLog::latest()->take(10)->get();
      
    • User-facing errors render automatically via the package’s exception handler (no manual render() needed).

Implementation Patterns

Core Workflows

  1. Throwing Exceptions:

    • Custom Exceptions: Extend Jftecnologia\LaravelExceptions\Exceptions\BaseException for domain-specific errors.
      class PaymentFailedException extends BaseException
      {
          public function __construct(string $message, string $userMessage = null)
          {
              parent::__construct($message, $userMessage, 402); // HTTP status code
          }
      }
      
    • Automatic Context: The package auto-collects:
      • User ID (if authenticated), IP, user agent, environment, and stack trace.
      • Override via ExceptionLog::setContext(['key' => 'value']).
  2. Logging Channels:

    • Configure in config/exceptions.php:
      'channels' => [
          'database' => true,
          'log' => env('APP_DEBUG', false), // Logs to Laravel's default channel
          'slack' => [
              'enabled' => env('EXCEPTIONS_SLACK_ENABLED', false),
              'webhook' => env('EXCEPTIONS_SLACK_WEBHOOK'),
          ],
      ],
      
    • Add custom channels by implementing Jftecnologia\LaravelExceptions\Contracts\ExceptionChannel.
  3. User-Friendly Messages:

    • Use i18n keys or direct strings:
      throw new CustomException('errors.user.not_found', 'Usuário não encontrado');
      
    • Override globally in config/exceptions.php:
      'user_messages' => [
          'Jftecnologia\LaravelExceptions\Exceptions\CustomException' => 'Algo deu errado. Tente novamente.',
      ],
      
  4. Handling HTTP Exceptions:

    • Convert Symfony exceptions (e.g., HttpException) automatically:
      throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('Route not found');
      
    • Customize HTTP status codes via the exception constructor.
  5. Middleware Integration:

    • Attach context dynamically in middleware:
      public function handle($request, Closure $next)
      {
          ExceptionLog::setContext(['request_id' => $request->header('X-Request-ID')]);
          return $next($request);
      }
      

Integration Tips

  • APIs: Return structured error responses by extending Jftecnologia\LaravelExceptions\Http\JsonExceptionRenderer.
  • Frontend: Use the user_message field in your error templates (e.g., Blade/React/Vue).
  • Monitoring: Query the exceptions table for analytics (e.g., error rates by endpoint).
  • Testing: Mock ExceptionLog in tests:
    $this->partialMock(ExceptionLog::class, function ($mock) {
        $mock->shouldReceive('store')->once();
    });
    

Gotchas and Tips

Pitfalls

  1. Context Overwriting:

    • setContext() overwrites existing context. Use addContext() (if available) or merge manually:
      ExceptionLog::setContext(array_merge(
          ExceptionLog::getContext(),
          ['custom_key' => 'value']
      ));
      
  2. Database Logging:

    • Large-scale apps may hit performance issues with heavy exception logging. Configure TTL via migration:
      $table->softDeletes(); // Add to exceptions table
      
    • Use EXCEPTIONS_LOG_LIMIT in .env to cap log volume.
  3. Symfony Exception Quirks:

    • Some Symfony exceptions (e.g., AccessDeniedHttpException) may not auto-convert. Extend the handler:
      use Jftecnologia\LaravelExceptions\Exceptions\BaseException;
      
      throw new BaseException(
          'Access denied',
          'Você não tem permissão para esta ação.',
          403,
          null,
          new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException()
      );
      
  4. Localization:

    • Ensure language files (resources/lang/) are published or manually added for multi-language support.
    • Fallback to en if translations are missing.
  5. Debugging:

    • Check ExceptionLog::getLastStored() to inspect the last logged exception.
    • Use EXCEPTIONS_DEBUG in .env to log raw exceptions to the console during development.

Tips

  1. Custom Channels:

    • Create a channel for error alerts (e.g., email, PagerDuty):
      class EmailExceptionChannel implements ExceptionChannel
      {
          public function send(ExceptionLog $log)
          {
              Mail::to('admin@example.com')->send(new ExceptionMail($log));
          }
      }
      
    • Register in config/exceptions.php:
      'channels' => [
          'email' => [
              'enabled' => true,
              'class' => \App\Channels\EmailExceptionChannel::class,
          ],
      ],
      
  2. Performance:

    • Disable database logging in production for non-critical errors:
      'channels' => [
          'database' => env('APP_ENV') !== 'production',
      ],
      
  3. Stack Trace:

    • Exclude sensitive paths (e.g., vendor/) from stack traces in production:
      'config' => [
          'exclude_paths' => [
              app_path('Vendor'),
              base_path('vendor'),
          ],
      ],
      
  4. Testing:

    • Assert exceptions are logged:
      $this->expectException(CustomException::class);
      // Then verify in database or mock the channel.
      
  5. Artisan Commands:

    • Clear old logs with:
      php artisan exceptions:prune --days=30
      
    • View recent errors:
      php artisan exceptions:list --limit=10
      
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.
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
anil/file-picker
broqit/fields-ai