src/Base/Controller/Api/ApiExceptionFormatter.php line 32

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