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

Api Exception Bundle Laravel Package

app-verk/api-exception-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require app-verk/api-exception-bundle
    
  2. Register the Bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3.x):
    AppVerk\ApiExceptionBundle\AppVerkApiExceptionBundle::class => ['all' => true],
    
  3. Enable the Bundle in config/packages/app_verk_api_exception.yaml:
    app_verk_api_exception:
        enabled: true
    

First Use Case

  • Trigger an Exception: Throw any exception (e.g., new \RuntimeException('Test error')) in a controller.
  • Observe the Response: The bundle automatically converts the error into a standardized application/problem+json response:
    {
      "detail": "Test error",
      "status": 500,
      "type": "about:blank",
      "title": "Internal Server Error"
    }
    

Implementation Patterns

Core Workflow

  1. Exception Handling:

    • The bundle catches all uncaught exceptions via ApiExceptionSubscriber and converts them into ApiProblem objects.
    • Useful for APIs where consistent error formats are critical (e.g., RESTful services).
  2. Customizing Responses:

    • Override the default response structure by implementing ResponseFactoryInterface:
      // src/Factory/CustomResponseFactory.php
      class CustomResponseFactory implements ResponseFactoryInterface {
          public function createResponse(ApiProblemInterface $apiProblem) {
              return new JsonResponse([
                  'error' => $apiProblem->toArray(),
                  'timestamp' => now()->toIso8601String(),
              ]);
          }
      }
      
    • Register the factory in config/packages/app_verk_api_exception.yaml:
      app_verk_api_exception:
          response_factory: App\Factory\CustomResponseFactory
      
  3. Excluding Paths:

    • Disable the bundle for specific routes (e.g., admin panels) via paths_excluded:
      app_verk_api_exception:
          paths_excluded: ['/admin/', '/_error']
      

Integration Tips

  • Symfony Serializer: Pair with symfony/serializer for complex error payloads (e.g., nested validation errors).
  • Logging: Combine with Monolog to log exceptions before converting them to responses:
    // In ApiExceptionSubscriber
    $logger->error($exception->getMessage(), ['exception' => $exception]);
    
  • Testing: Mock ResponseFactoryInterface in unit tests to assert response formats:
    $factory = $this->createMock(ResponseFactoryInterface::class);
    $factory->expects($this->once())
            ->method('createResponse')
            ->willReturn(new JsonResponse(['custom' => 'data']));
    $this->container->set(ResponseFactoryInterface::class, $factory);
    

Gotchas and Tips

Pitfalls

  1. Symfony 5+ Compatibility:

    • The bundle targets Symfony 3.3+, but Symfony 5+ requires explicit bundle registration in config/bundles.php (not AppKernel).
    • Fix: Ensure the bundle is listed under config/bundles.php with all: true.
  2. Overriding Default Factory:

    • Forgetting to set response_factory in config will use the default factory, which may not match your API’s error schema.
    • Tip: Always explicitly configure the factory to avoid surprises.
  3. Paths Exclusion:

    • Paths in paths_excluded are case-sensitive and must match the exact route path (including trailing slashes).
    • Example: Exclude /api/v1/users but not /api/v1/users/.
  4. Performance Impact:

    • The subscriber runs on every request, even for successful ones. For high-traffic APIs, consider:
      • Disabling the bundle for non-API routes.
      • Using a lighter-weight error handler for non-critical paths.

Debugging

  1. No Response Conversion:

    • Check if enabled: false in config or the subscriber is not registered (Symfony 5+ bundles.php).
    • Debug: Add a dump() in ApiExceptionSubscriber::onKernelException() to verify the subscriber is triggered.
  2. Custom Factory Not Loading:

    • Ensure the factory class is autoloaded (e.g., placed in src/ and namespaced correctly).
    • Debug: Clear cache (php bin/console cache:clear) and check Symfony’s debug toolbar for errors.
  3. RFC7807 Compliance:

    • The default type field uses about:blank. Override it in your factory for meaningful URIs (e.g., /problems/invalid-request):
      $apiProblem->setType('/api/problems/' . strtolower($exception->getMessage()));
      

Extension Points

  1. Add Custom Fields:

    • Extend ApiProblem by creating a custom class:
      class CustomApiProblem extends ApiProblem {
          public function setAdditionalData(array $data) {
              $this->additional = $data;
          }
      }
      
    • Use it in your factory:
      $problem = new CustomApiProblem(400, 'Bad Request');
      $problem->setAdditionalData(['validation_errors' => $errors]);
      
  2. Conditional Handling:

    • Filter exceptions in the subscriber:
      if ($exception instanceof \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface) {
          // Handle HTTP exceptions differently
      }
      
  3. Localization:

    • Localize error messages by injecting a translator into the factory:
      public function __construct(private TranslatorInterface $translator) {}
      public function createResponse(ApiProblemInterface $apiProblem) {
          $apiProblem->setTitle($this->translator->trans($apiProblem->getTitle()));
      }
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
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