src/Controller/Api/DomainExceptionFormatter.php line 29

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Controller\Api;
  4. use App\Controller\ErrorHandler;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. class DomainExceptionFormatter implements EventSubscriberInterface
  10. {
  11.     private $errors;
  12.     public function __construct(ErrorHandler $errors)
  13.     {
  14.         $this->errors $errors;
  15.     }
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return array(
  19.             KernelEvents::EXCEPTION => 'onKernelException'
  20.         );
  21.     }
  22.     public function onKernelException(ExceptionEvent $event): void
  23.     {
  24.         $exception $event->getThrowable();
  25.         $request $event->getRequest();
  26.         if (!$exception instanceof \DomainException) {
  27.             return;
  28.         }
  29.         if (strpos($request->attributes->get('_route'), 'api') !== 0) {
  30.             return;
  31.         }
  32.         $this->errors->handle($exception);
  33.         $event->setResponse(new JsonResponse([
  34.             'error' => [
  35.                 'code' => 400,
  36.                 'message' => $exception->getMessage(),
  37.             ]
  38.         ], 400));
  39.     }
  40. }