<?php
namespace App\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Translation\TranslatorInterface;
use App\Exception\ExceptionWithTemplateHtml;
use App\Exception\EntityException;
use App\Exception\MailerException;
class ExceptionListener
{
protected $translator;
protected $twig;
public function __construct(TranslatorInterface $translator, $twig)
{
$this->translator = $translator;
$this->twig = $twig;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
// You get the exception object from the received event
$exception = $event->getException();
//only for exception from listener
if($exception->getMessage() == $this->translator->trans('listener.accesstoken.confirmation')) {
// $message = sprintf(
// 'My Error says: %s with code: %s',
// $exception->getMessage(),
// $exception->getCode()
// );
// Customize your response object to display the exception details
$response = new Response();
$response->setContent(json_encode(array('error' => 'invalid_confirmation', 'error_description' => $exception->getMessage())));
// HttpExceptionInterface is a special type of exception that
// holds status code and header details
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
} else {
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}
// Send the modified response object to the event
$event->setResponse($response);
}
// Depuis la désactivation du mode debug dans le seconde param du AppKernel, la gestion des erreurs n'est plus la même. Il récupère l'exception pour la formatter
else {
$exceptionCode = !method_exists($exception, 'getStatusCode') ? 400 : $exception->getStatusCode();
$content = array(
'code' => $exceptionCode,
'message' => $exception->getMessage(),
);
// Si c'est un excption html, doit former le template html
if ($exception instanceof ExceptionWithTemplateHtml) {
$content['template'] = $this->twig->render($exception->template, ['data' => $exception->data]);
$content['reasons'] = $exception->data['reasons'];
}
if (($exception instanceof EntityException || $exception instanceof MailerException) && isset($exception->codeError)) {
$content['message'] = $this->translator->trans($exception->codeError);
}
$response = new Response();
$response->setContent(json_encode($content));
$response->setStatusCode($exceptionCode);
$exceptionCode = method_exists($exception, 'getHeaders') ? $response->headers->replace($exception->getHeaders()) : null;
$event->setResponse($response);
}
return;
}
}