<?php
namespace App\EventListener;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ExceptionListener
{
public const HEADERS = ['Content-Type' => 'application/problem+json; charset=utf-8'];
public function onKernelException(ExceptionEvent $event): void
{
if ('prod' === getenv('APP_ENV')) {
$exception = $event->getThrowable();
switch ($exception) {
case $exception instanceof NotFoundHttpException:
$this->handleNotFoundHttpException($event);
break;
default:
$this->handleDefaultException($event);
break;
}
}
}
private function handleNotFoundHttpException(ExceptionEvent $event): void
{
$event->setResponse(
new JsonResponse(
$this->getFormatedError($event->getThrowable()->getMessage()),
Response::HTTP_NOT_FOUND,
self::HEADERS
)
);
}
private function handleDefaultException(ExceptionEvent $event): void
{
$appDebug = getenv('APP_DEBUG');
if (!$appDebug) {
$event->setResponse(
new JsonResponse(
$this->getFormatedError('An error occurred. please try again or contact the administrator'),
Response::HTTP_INTERNAL_SERVER_ERROR,
self::HEADERS
)
);
}
}
private function getFormatedError(string $message): array
{
return [
'title' => 'Validation Failed',
'detail' => str_replace('"', "'", $message),
];
}
}