src/EventListener/ApiExceptionSubscriber.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Utils\ExceptionCodes;
  4. use ReflectionClass;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\Exception\HttpException;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. class ApiExceptionSubscriber implements EventSubscriberInterface
  11. {
  12.     /**
  13.      * Handles the response of any "App" Exception, displaying error code and message depending on the debug policy.
  14.      * @param ExceptionEvent $event
  15.      */
  16.     public function onKernelException(ExceptionEvent $event): void
  17.     {
  18.         $e $event->getThrowable();
  19.         if (!$e instanceof HttpException) {
  20.             // not an App Exception: no treatment
  21.             return;
  22.         }
  23.         // retrieving all valid codes
  24.         $codes = (new ReflectionClass(ExceptionCodes::class))->getConstants();
  25.         $data = [
  26.             'error_code' => in_array((string) $e->getCode(), $codes) ? $e->getCode() : 0,
  27.             'error_status' => $e->getStatusCode(),
  28.         ];
  29.         // message and trace are displayed only in DEBUG mode
  30.         if ($_ENV['APP_DEBUG']) {
  31.             $data['error_message'] = $e->getMessage();
  32.             $data['error_trace'] = $e->getTrace();
  33.         }
  34.         $response = new JsonResponse($data$e->getStatusCode());
  35.         $response->headers->set('Content-Type''application/problem+json');
  36.         $event->setResponse($response);
  37.     }
  38.     /**
  39.      * @return string[]
  40.      */
  41.     public static function getSubscribedEvents(): array
  42.     {
  43.         return array(
  44.             KernelEvents::EXCEPTION => 'onKernelException'
  45.         );
  46.     }
  47. }