<?php
namespace ApiBundle\EventListener;
use ApiBundle\Api\Util\ExceptionUtil;
use ApiBundle\ApiBundle;
use ApiBundle\Viewer;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
class ExceptionListener
{
private $container;
private $viewer;
public function __construct(ContainerInterface $container, Viewer $viewer)
{
$this->container = $container;
$this->viewer = $viewer;
}
public function onKernelException(ExceptionEvent $event)
{
if (!$this->isApiPath($event->getRequest())) {
return;
}
$exception = $event->getThrowable();
list($error, $httpCode) = ExceptionUtil::getErrorAndHttpCodeFromException($exception, $this->isDebug());
$error['message'] = $this->container->get('translator')->trans($error['message']);
$response = $this->viewer->view(['error' => $error], $httpCode);
$event->setResponse($response);
$event->stopPropagation();
}
private function isApiPath($request)
{
return str_contains($request->getPathInfo(), ApiBundle::API_PREFIX);
}
private function isDebug()
{
return $this->container->get('kernel')->isDebug();
}
}