Eviter l’erreur récurrente NotFoundHttpException dans vos logs

Quand vous cherchez à réduire vos logs à zéro au lancement de votre site en production Symfony2, il se peut que vous rencontriez des exceptions de type NotFoundHttpException.

Le mieux pour cela est de surcharger la classe Symfony\Component\HttpKernel\EventListener\ExceptionListener comme suit et de les rediriger vers une page 404.

public function onKernelException(GetResponseForExceptionEvent $event)
{
static $handling;

if (true === $handling) {
return false;
}

$handling = true;

$exception = $event->getException();
$request = $event->getRequest();

if (null !== $this->logger) {
$message = sprintf('%s: %s (uncaught exception) at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine());
if (!$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500) {
$this->logger->crit($message);
} else {
$this->logger->err($message);
}
} else {
error_log(sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine()));
}

$logger = $this->logger instanceof DebugLoggerInterface ? $this->logger : null;

$attributes = array(
'_controller' => $this->controller,
'exception' => FlattenException::create($exception),
'logger' => $logger,
'format' => $request->getRequestFormat(),
);

$request = $request->duplicate(null, null, $attributes);
$request->setMethod('GET');

try {
$response = $event->getKernel()->handle($request, HttpKernelInterface::SUB_REQUEST, true);
} catch (\Exception $e) {

//Cas d'une erreur NotFoundHttpException
if($e instanceof NotFoundHttpException){
$response = new Response(Response::$statusTexts[404], 404);
$event->setResponse($response);
return;
}

$message = sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $e->getMessage());
if (null !== $this->logger) {
if (!$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500) {
$this->logger->crit($message);
} else {
$this->logger->err($message);
}
} else {
error_log($message);
}

// set handling to false otherwise it wont be able to handle further more
$handling = false;

// re-throw the exception from within HttpKernel as this is a catch-all
return;
}

$event->setResponse($response);

$handling = false;
}

Ensuite, il faut ajouter le paramètre suivant dans votre parameters.yml

twig.exception_listener.class: “NameSpace\VotreBundle\EventListener\ExceptionListener”