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

Custom Exception Handler Laravel Package

bytestechnolabs/custom-exception-handler

Laravel package for configurable exception handling: map exception classes to custom messages, HTTP status codes, and extra response data via config. Includes helper to add custom data dynamically during catch blocks for consistent API error responses.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bytestechnolabs/custom-exception-handler
    

    Publish the config file (if provided):

    php artisan vendor:publish --provider="ByteScode\CustomExceptionHandler\CustomExceptionHandlerServiceProvider"
    
  2. Basic Usage Register the package in config/app.php under providers:

    ByteScode\CustomExceptionHandler\CustomExceptionHandlerServiceProvider::class,
    
  3. First Use Case Extend Laravel’s default exception handling by overriding App\Exceptions\Handler.php:

    use ByteScode\CustomExceptionHandler\CustomExceptionHandler;
    
    public function render($request, Throwable $exception)
    {
        return CustomExceptionHandler::handle($request, $exception);
    }
    
  4. Default Configuration Check config/custom-exception-handler.php for:

    • Global exception mappings (e.g., 404, 500).
    • Response formats (JSON, HTML, API).
    • Logging thresholds.

Implementation Patterns

Core Workflows

  1. Exception Mapping Define custom responses per exception type in config/custom-exception-handler.php:

    'mappings' => [
        \App\Exceptions\ValidationException::class => [
            'status' => 422,
            'format' => 'json',
            'template' => 'errors.validation',
        ],
    ],
    
  2. Dynamic Handling Use middleware to inject context (e.g., user roles):

    public function handle($request, Closure $next)
    {
        $request->merge(['user_role' => auth()->user()->role]);
        return $next($request);
    }
    
  3. API vs. Web Responses Differentiate responses based on request type:

    if ($request->wantsJson()) {
        return CustomExceptionHandler::formatJson($exception);
    }
    return CustomExceptionHandler::formatHtml($exception);
    
  4. Logging Integration Log exceptions conditionally:

    if (config('custom-exception-handler.log_level') === 'critical') {
        Log::critical($exception);
    }
    

Integration Tips

  • Laravel Mix/Vite: Use the package’s template config to render error views in your frontend build.
  • Testing: Mock CustomExceptionHandler in PHPUnit:
    $handler = $this->app->make(CustomExceptionHandler::class);
    $response = $handler->handle($request, new \Exception('Test'));
    
  • Queue Failures: Extend the handler to log failed jobs:
    if ($exception instanceof \Illuminate\Bus\QueueingFailedJob) {
        // Custom logic for queue failures
    }
    

Gotchas and Tips

Pitfalls

  1. Config Overrides

    • Avoid naming conflicts with Laravel’s default App\Exceptions\Handler. Use a unique namespace (e.g., App\Handlers\CustomExceptionHandler).
    • Fix: Merge configs explicitly:
      $config = array_merge(
          require __DIR__.'/custom-exception-handler.php',
          config('custom-exception-handler', [])
      );
      
  2. Circular Dependencies

    • If the package relies on App\Exceptions\Handler, ensure it’s autoloaded before the package’s service provider.
    • Fix: Reorder providers in config/app.php.
  3. Performance

    • Heavy exception logic (e.g., database checks) in render() can slow responses.
    • Fix: Offload to middleware or jobs.
  4. Missing Templates

    • If a template (e.g., errors.validation) is missing, the handler may throw a ViewNotFoundException.
    • Fix: Provide a fallback:
      CustomExceptionHandler::setFallbackTemplate('errors.default');
      

Debugging

  • Log Dumping: Enable debug mode in config/custom-exception-handler.php:
    'debug' => env('APP_DEBUG', false),
    
  • Exception Tracing: Use dd($exception) in render() to inspect the exception object structure.

Extension Points

  1. Custom Formats Extend the handler to support new formats (e.g., XML):

    CustomExceptionHandler::extend('xml', function ($exception) {
        return response()->xml($exception->getMessage());
    });
    
  2. Event Listeners Listen for exception events to pre-process exceptions:

    Event::listen(ExceptionOccurred::class, function ($event) {
        $event->exception->setCustomAttribute('user_id', auth()->id());
    });
    
  3. Localization Override error messages via language files:

    // resources/lang/en/errors.php
    return [
        'validation' => 'Custom validation error message.',
    ];
    

    Then reference in config:

    'mappings' => [
        \App\Exceptions\ValidationException::class => [
            'message' => __('errors.validation'),
        ],
    ],
    
  4. Testing Edge Cases Test with:

    • Nested exceptions ($exception->getPrevious()).
    • Localized responses ($request->header('Accept-Language')).
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager