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

Handler Exception Laravel Package

bensonirah/handler-exception

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bensonirah/handler-exception
    

    Register the service provider in config/app.php:

    'providers' => [
        // ...
        Bensonirah\HandlerException\HandlerExceptionServiceProvider::class,
    ],
    
  2. Basic Configuration Publish the config file:

    php artisan vendor:publish --provider="Bensonirah\HandlerException\HandlerExceptionServiceProvider" --tag="config"
    

    Edit config/handler-exception.php to define your exception handlers (e.g., App\Exceptions\Handler or custom classes).

  3. First Use Case Define a handler for a specific exception in config/handler-exception.php:

    'handlers' => [
        \App\Exceptions\CustomException::class => \App\Http\Controllers\ExceptionController::class,
    ],
    

    Trigger an exception in your controller:

    throw new \App\Exceptions\CustomException('Test error');
    

    The package will automatically route it to ExceptionController.


Implementation Patterns

Centralized Exception Handling

  • Symfony-Style Integration: Leverage Symfony’s ExceptionListener and ExceptionHandler interfaces for structured handling.
    use Bensonirah\HandlerException\Contracts\ExceptionHandlerInterface;
    
    class CustomExceptionHandler implements ExceptionHandlerInterface
    {
        public function handle(\Throwable $exception, $code)
        {
            return response()->json(['error' => $exception->getMessage()], $code);
        }
    }
    
    Register in config/handler-exception.php:
    'handlers' => [
        \App\Exceptions\CustomException::class => CustomExceptionHandler::class,
    ],
    

Dynamic Routing

  • Use middleware to dynamically assign handlers based on request context (e.g., API vs. web):
    // app/Http/Middleware/AssignExceptionHandler.php
    public function handle($request, Closure $next)
    {
        if ($request->is('api/*')) {
            config(['handler-exception.handlers' => [
                \App\Exceptions\ApiException::class => \App\Http\Controllers\ApiExceptionController::class,
            ]]);
        }
        return $next($request);
    }
    

Grouped Handlers

  • Handle multiple exceptions with a single controller:
    'handlers' => [
        [
            \App\Exceptions\ValidationException::class,
            \App\Exceptions\AuthException::class,
        ] => \App\Http\Controllers\GlobalExceptionController::class,
    ],
    

Logging and Monitoring

  • Extend the base handler to integrate with logging/monitoring tools (e.g., Sentry, Laravel Log):
    use Illuminate\Support\Facades\Log;
    
    class LoggingExceptionHandler implements ExceptionHandlerInterface
    {
        public function handle(\Throwable $exception, $code)
        {
            Log::error($exception->getMessage(), ['exception' => $exception]);
            return response()->json(['error' => 'Internal Server Error'], $code);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Config Overrides

    • Avoid hardcoding handlers in App\Exceptions\Handler if using this package, as it may conflict with the centralized config.
    • Fix: Use the package’s config exclusively or merge logic carefully.
  2. Middleware Order

    • Ensure the HandlerExceptionMiddleware runs after your app’s middleware (e.g., auth, verified) to avoid premature exception handling.
    • Fix: Place it at the end of $middlewareGroups['web'] or $middlewareGroups['api'].
  3. Circular Dependencies

    • If your exception handler throws another exception, it may cause infinite loops.
    • Fix: Add a guard in your handler:
      if ($exception instanceof \Bensonirah\HandlerException\Exceptions\HandlerException) {
          return response()->json(['error' => 'Handler error'], 500);
      }
      

Debugging Tips

  1. Verify Handler Registration

    • Check if your handler is registered in config/handler-exception.php. Use:
      php artisan config:clear
      
      to reset cached config.
  2. Log Unhandled Exceptions

    • Enable Laravel’s debug mode (APP_DEBUG=true) to log unhandled exceptions to storage/logs/laravel.log.
  3. Test Edge Cases

    • Test with:
      • Nested exceptions (e.g., try-catch throwing a new exception).
      • Non-HTTP exceptions (e.g., RuntimeException).
      • Custom HTTP status codes.

Extension Points

  1. Custom Exception Classes

    • Extend Bensonirah\HandlerException\Exceptions\HandlerException for domain-specific exceptions:
      class PaymentException extends HandlerException {}
      
  2. Event Listeners

    • Listen to exception.handled events to perform post-handling actions:
      Event::listen('exception.handled', function ($exception, $handler) {
          // Send notification, update analytics, etc.
      });
      
  3. API Responses

    • Standardize API error responses by creating a base handler:
      class ApiExceptionHandler implements ExceptionHandlerInterface
      {
          public function handle(\Throwable $exception, $code)
          {
              return response()->json([
                  'success' => false,
                  'error'   => $exception->getMessage(),
                  'code'    => $code,
              ], $code);
          }
      }
      
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor