src/EventSubscriber/InternalErrorSubscriber.php line 39

  1. <?php
  2. namespace App\EventSubscriber;
  3. use Psr\Log\LoggerInterface;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. /**
  10.  * Answers every failure under /internal/ as a short JSON body, never as Symfony's error page.
  11.  *
  12.  * With APP_DEBUG on, the error page shows the code, the query and the settings around a
  13.  * failure. The account API never passes a page on to a browser, but it should not receive one
  14.  * either. A failure of this service is logged here in full and answered as 500 with one
  15.  * sentence; an address that names no route, or a method a route does not take, keeps its own
  16.  * status (404, 405).
  17.  */
  18. final class InternalErrorSubscriber implements EventSubscriberInterface
  19. {
  20.     private const SENTENCES = [
  21.         400 => 'Bad request',
  22.         404 => 'Not found',
  23.         405 => 'Method not allowed',
  24.     ];
  25.     public function __construct(private LoggerInterface $logger)
  26.     {
  27.     }
  28.     public static function getSubscribedEvents(): array
  29.     {
  30.         // Before Symfony's own error listener, which listens at -128 and renders the page.
  31.         return [KernelEvents::EXCEPTION => ['onKernelException', 10]];
  32.     }
  33.     public function onKernelException(ExceptionEvent $event): void
  34.     {
  35.         if (!ServiceKeySubscriber::isInternal($event->getRequest()->getPathInfo())) {
  36.             return;
  37.         }
  38.         $error = $event->getThrowable();
  39.         if ($error instanceof HttpExceptionInterface && $error->getStatusCode() < 500) {
  40.             $status = $error->getStatusCode();
  41.             $event->setResponse(new JsonResponse(
  42.                 ['error' => self::SENTENCES[$status] ?? 'Request refused'],
  43.                 $status,
  44.                 $error->getHeaders()
  45.             ));
  46.             return;
  47.         }
  48.         $this->logger->error('[internal] ' . $error->getMessage(), ['exception' => $error]);
  49.         $event->setResponse(new JsonResponse(['error' => 'The social service failed'], 500));
  50.     }
  51. }