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

Exception Handler Bundle Laravel Package

amontreuil/exception-handler-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require amontreuil/exception-handler-bundle
    

    No additional configuration is required—exceptions are auto-loaded via PSR-4 autoloading.

  2. First Use Case Throw a BadRequestException for missing/invalid data:

    use Amontreuil\ExceptionHandlerBundle\Exception\BadRequestException;
    
    if (empty($request->input('required_field'))) {
        throw new BadRequestException('The required data is missing.');
    }
    
  3. Where to Look First

    • Exceptions List: Review src/Exception for available exceptions.
    • HTTP Status Codes: All exceptions align with REST standards (e.g., 400, 404, 503).

Implementation Patterns

Core Workflows

  1. Validation Errors Use BadRequestException or BadFormPostException for form/data validation:

    if (!$validator->passes()) {
        throw new BadRequestException('Validation failed: ' . implode(', ', $validator->errors()));
    }
    
  2. API-Specific Errors

    • Media Type Mismatch: UnsupportedMediaTypeApiException
      if (!$request->isJson()) {
          throw new UnsupportedMediaTypeApiException('Content-Type must be application/json.');
      }
      
    • UUID Validation: BadUuidException
      if (!Uuid::isValid($uuid)) {
          throw new BadUuidException("Invalid UUID: {$uuid}");
      }
      
  3. Forbidden/Unauthorized

    • 401 Unauthorized: UnauthorizedRequestException
      if (!$user->hasRole('admin')) {
          throw new UnauthorizedRequestException('Access denied.');
      }
      
    • 403 Forbidden: ForbiddenRequestException
      if ($resource->isPrivate() && !$user->owns($resource)) {
          throw new ForbiddenRequestException('You do not have permission to access this resource.');
      }
      
  4. Duplicate Data Use DuplicateDataException with context:

    if ($existingRecord = User::where('email', $email)->first()) {
        throw new DuplicateDataException("Email {$email} is already in use.");
    }
    
  5. Custom Rules Violations ViolationRuleRequestException for business logic breaches:

    if ($user->isSuspended()) {
        throw new ViolationRuleRequestException('Account is suspended.');
    }
    

Integration Tips

  • Symfony Event Listeners: Extend the bundle’s ExceptionListener to customize responses (e.g., add metadata to JSON errors).
  • API Controllers: Centralize exception handling in a base controller:
    use Symfony\Component\HttpFoundation\JsonResponse;
    use Amontreuil\ExceptionHandlerBundle\Exception\ApiException;
    
    class BaseController extends Controller {
        public function handleException(ApiException $e): JsonResponse {
            return new JsonResponse([
                'error' => $e->getMessage(),
                'status' => $e->getStatusCode(),
            ], $e->getStatusCode());
        }
    }
    
  • Testing: Mock exceptions in unit tests:
    $this->expectException(BadRequestException::class);
    $this->expectExceptionMessage('The required data is missing.');
    

Gotchas and Tips

Pitfalls

  1. Namespace Conflicts

    • The bundle uses Amontreuil\ExceptionHandlerBundle\Exception namespace. Ensure no naming collisions with other packages (e.g., custom Exception classes).
  2. Status Code Deviations

    • Custom codes like 452 (BadFormPostException) or 453 (BadUuidException) are non-standard. Document these in your API specs to avoid client confusion.
  3. Optional Parameters in ApiException

    • Fixed in v2.0.3, but older versions may require explicit constructor arguments:
      // Older versions might need:
      new BadRequestException('Message', [], 400);
      
  4. Symfony Version Lock

    • Requires Symfony 5.0+. Avoid mixing with older Symfony versions (e.g., 4.x).

Debugging Tips

  • Check HTTP Status Codes: Use browser dev tools or dd($exception->getStatusCode()) to verify the correct code is thrown.
  • Log Exceptions: Wrap throws in a try-catch to log context:
    try {
        // Risky operation
    } catch (BadUuidException $e) {
        \Log::error("Invalid UUID {$uuid}: " . $e->getMessage());
        throw $e;
    }
    

Extension Points

  1. Custom Exceptions Extend ApiException to create project-specific exceptions:

    namespace App\Exception;
    
    use Amontreuil\ExceptionHandlerBundle\Exception\ApiException;
    
    class InvalidPaymentException extends ApiException {
        public function __construct(string $message) {
            parent::__construct($message, [], 400);
        }
    }
    
  2. Override Exception Listener Replace the bundle’s ExceptionListener in config/services.yaml:

    services:
        App\EventListener\CustomExceptionListener:
            tags:
                - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
    
  3. Add Metadata to Responses Extend the ApiException constructor to include extra data:

    new BadRequestException('Invalid input.', ['field' => 'email', 'rule' => 'required'], 400);
    

    Then customize the listener to serialize this into the response.

  4. Localization Use Symfony’s translation system to localize messages:

    throw new BadRequestException($this->translator->trans('validation.required', ['%field%' => 'email']));
    
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle