src/EventListener/ExceptionListener.php line 24

Open in your IDE?
  1. <?php
  2. /**
  3.  * Exception Listener custom render json-ld
  4.  *
  5.  * @package RMCS
  6.  * @author Vlad Shashkov  <vlad.s@zimalab.com>
  7.  * @copyright 2014 - 2019 The Zimalab
  8.  */
  9. declare(strict_types=1);
  10. namespace App\EventListener;
  11. use ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException;
  12. use Symfony\Component\HttpFoundation\{JsonResponseResponse};
  13. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  14. class ExceptionListener
  15. {
  16.     /**
  17.      * Event exception errors
  18.      *
  19.      * @param ExceptionEvent $event
  20.      */
  21.     public function onKernelException(ExceptionEvent $event): void
  22.     {
  23.         $exception $event->getException();
  24.         if (!$exception instanceof ValidationException) {
  25.             $request $event->getRequest();
  26.             $response = [
  27.                 '@id' => $request->getHost(),
  28.                 '@type' => 'error',
  29.                 '@context' => [
  30.                     'code' => $exception->getCode(),
  31.                     'message' => $exception->getMessage(),
  32.                 ],
  33.             ];
  34.             if ($_ENV['APP_ENV'] == 'dev') {
  35.                 $response['@context']['trace'] = $exception->getTrace();
  36.             }
  37.             if ($exception->getMessage() == 'Syntax error') {
  38.                 $event->setResponse(new JsonResponse(
  39.                     $response,
  40.                     Response::HTTP_BAD_REQUEST
  41.                 ));
  42.             } else {
  43.                 $event->setResponse(new JsonResponse(
  44.                     $response
  45.                 ));
  46.             }
  47.         }
  48.     }
  49. }