src/EventSubscriber/ApiExceptionSubscriber.php line 33

Open in your IDE?
  1. <?php
  2. namespace Seidemann\Hanagud\EventSubscriber;
  3. use Seidemann\Hanagud\Http\ApiResponse;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\DataCollector\ExceptionDataCollector;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use Symfony\Component\HttpKernel\Profiler\Profiler;
  11. use Throwable;
  12. class ApiExceptionSubscriber implements EventSubscriberInterface
  13. {
  14.     public function __construct(private ?Profiler $profiler null)
  15.     {
  16.     }
  17.     /**
  18.      * Creates the ApiResponse from any Exception.
  19.      */
  20.     private function createApiResponse(Throwable $exception): ApiResponse
  21.     {
  22.         $statusCode $exception instanceof HttpExceptionInterface
  23.             $exception->getStatusCode()
  24.             : Response::HTTP_INTERNAL_SERVER_ERROR;
  25.         return new ApiResponse(null$exception$statusCode);
  26.     }
  27.     public function onKernelException(ExceptionEvent $event): void
  28.     {
  29.         $exception $event->getThrowable();
  30.         $request $event->getRequest();
  31.         if (in_array('application/json'$request->getAcceptableContentTypes())) {
  32.             $response $this->createApiResponse($exception);
  33.             $event->setResponse($response);
  34.             // If profiler is enabled, log exception into it
  35.             if (null !== $this->profiler) {
  36.                 $exceptionCollector $this->profiler->get('exception');
  37.                 /* @var ExceptionDataCollector $exceptionCollector */
  38.                 $exceptionCollector->collect($request$response$exception);
  39.             }
  40.         }
  41.     }
  42.     public static function getSubscribedEvents()
  43.     {
  44.         return [
  45.             KernelEvents::EXCEPTION => [
  46.                 ['onKernelException', -9],
  47.             ],
  48.         ];
  49.     }
  50. }