<?php
namespace Rawafed\CommonsBundle\Service;
use Monolog\Logger;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Contracts\Translation\TranslatorInterface;
use Rawafed\CommonsBundle\Exception\ApplicationException;
class ExceptionListener
{
private $kernelEnvironment;
private $logger;
private $translator;
public function __construct(string $kernelEnvironment, Logger $logger, TranslatorInterface $translator)
{
$this->kernelEnvironment = $kernelEnvironment;
$this->logger = $logger;
$this->translator = $translator;
}
public function onKernelException(ExceptionEvent $event)
{
// handle ajax exception to return json response
if ($event->getRequest()->isXmlHttpRequest() && ($this->kernelEnvironment != 'dev')) {
$exception = $event->getThrowable();
$message = null;
if ($exception instanceof ApplicationException) {
$message = $exception->getMessage();
} else {
$message = 'Internal Server Error';
$this->logger->addError($exception);
}
$event->setResponse(
new JsonResponse(array('error' => true, 'message' => $this->translator->trans($message)), 500)
);
}
}
}