src/ApiV3Bundle/Listener/ApiV3ExceptionListener.php line 23

Open in your IDE?
  1. <?php
  2. namespace ApiV3Bundle\Listener;
  3. use ApiV3Bundle\ApiV3Bundle;
  4. use AppBundle\Common\ExceptionPrintingToolkit;
  5. use Symfony\Component\DependencyInjection\ContainerInterface;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  9. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  10. use Throwable;
  11. class ApiV3ExceptionListener
  12. {
  13.     private $container;
  14.     public function __construct(ContainerInterface $container)
  15.     {
  16.         $this->container $container;
  17.     }
  18.     public function onKernelException(ExceptionEvent $event)
  19.     {
  20.         if (!$this->isApiPath($event->getRequest())) {
  21.             return;
  22.         }
  23.         $exception $event->getThrowable();
  24.         $data $this->buildResponseData($exception);
  25.         $statusCode $this->getStatusCode($exception);
  26.         $response = new JsonResponse($data$statusCode);
  27.         $event->setResponse($response);
  28.         $event->stopPropagation();
  29.     }
  30.     private function buildResponseData(Throwable $exception): array
  31.     {
  32.         $data = [
  33.             'status' => false,
  34.             'message' => 'Internal server error',
  35.             'code' => $exception->getCode() ?: 0,
  36.         ];
  37.         if ($this->isDebug()) {
  38.             $data['message'] = $this->container->get('translator')->trans($exception->getMessage());
  39.             $data['trace'] = ExceptionPrintingToolkit::printTraceAsArray($exception);
  40.         } else if ($exception instanceof HttpExceptionInterface) {
  41.             $data['message'] = $this->container->get('translator')->trans($exception->getMessage());
  42.         } else {
  43.             $this->container->get('biz')->offsetGet('logger')->error('[V3Exception] ' $exception->getMessage(), ExceptionPrintingToolkit::printTraceAsArray($exception));
  44.         }
  45.         return $data;
  46.     }
  47.     private function getStatusCode(Throwable $exception): int
  48.     {
  49.         if ($exception instanceof HttpExceptionInterface) {
  50.             return $exception->getStatusCode();
  51.         }
  52.         return Response::HTTP_INTERNAL_SERVER_ERROR;
  53.     }
  54.     private function isApiPath($request)
  55.     {
  56.         return false !== strpos($request->getPathInfo(), ApiV3Bundle::API_PREFIX '/');
  57.     }
  58.     private function isDebug()
  59.     {
  60.         return $this->container->get('kernel')->isDebug();
  61.     }
  62. }