src/EventListener/ExceptionSubscriber.php line 31

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventListener;
  4. use Neomerx\JsonApi\Document\Document;
  5. use Neomerx\JsonApi\Document\Error;
  6. use Symfony\Component\Debug\Exception\FlattenException;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
  12. final class ExceptionSubscriber implements EventSubscriberInterface
  13. {
  14.     private const EXCEPTION_STATUS_MAP = [
  15.         AuthenticationCredentialsNotFoundException::class => 401,
  16.     ];
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             KernelEvents::EXCEPTION => [
  21.                 ['onKernelException', -100],
  22.             ],
  23.         ];
  24.     }
  25.     public function onKernelException(GetResponseForExceptionEvent $event): void
  26.     {
  27.         $document = new Document();
  28.         $error = new Error();
  29.         $exception $event->getException();
  30.         $exceptionClass = \get_class($exception);
  31.         $exception FlattenException::create($exception);
  32.         $statusCode self::EXCEPTION_STATUS_MAP[$exceptionClass] ?? $exception->getStatusCode();
  33.         $error->setStatus((string) $statusCode);
  34.         $error->setTitle(JsonResponse::$statusTexts[$statusCode] ?? null);
  35.         $document->addError($error);
  36.         $document->addJsonApiVersion('1.0');
  37.         $event->setResponse(new JsonResponse($document->getDocument(), $statusCode, [
  38.             'Content-Type' => 'application/vnd.api+json',
  39.         ]));
  40.     }
  41. }