<?php
namespace App\Listeners;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\{JsonResponse, Response};
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class NotFoundListener implements EventSubscriberInterface
{
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
if ($exception instanceof NotFoundHttpException) {
$event->allowCustomResponseCode();
$response = new JsonResponse(
[
'result' => false,
'message' => $exception->getMessage()
],
Response::HTTP_NOT_FOUND
);
$event->setResponse($response);
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::EXCEPTION => [
['onKernelException', 64]
]
];
}
}