bundles/Jabber/RestApiBundle/EventListener/ExceptionListener.php line 15

Open in your IDE?
  1. <?php
  2. namespace Jabber\RestApiBundle\EventListener;
  3. use Jabber\RestApiBundle\Http\ApiResponse;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  6. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  7. class ExceptionListener
  8. {
  9.     /**
  10.      * @param ExceptionEvent $event
  11.      */
  12.     public function onKernelException(ExceptionEvent $event)
  13.     {
  14.         $exception $event->getThrowable();
  15.         $request   $event->getRequest();
  16.         if (str_starts_with($request->getPathInfo(), "/api/")) {
  17.             $response $this->createApiResponse($exception);
  18.             $event->setResponse($response);
  19.         }
  20.     }
  21.     
  22.     /**
  23.      * Creates the ApiResponse from any Exception
  24.      *
  25.      * @param \Exception $exception
  26.      *
  27.      * @return ApiResponse
  28.      */
  29.     private function createApiResponse(\Throwable $exception$errors = [])
  30.     {
  31.         if ($exception instanceof HttpExceptionInterface) {
  32.             $statusCode $exception->getStatusCode() ?? Response::HTTP_INTERNAL_SERVER_ERROR;
  33.         } else {
  34.             $statusCode $exception->getCode() ?? Response::HTTP_INTERNAL_SERVER_ERROR;
  35.         }
  36.         if ($statusCode == 0) {
  37.             $statusCode Response::HTTP_INTERNAL_SERVER_ERROR;
  38.         }
  39.         return new ApiResponse($exception->getMessage(), null$errors$statusCode);
  40.     }
  41. }