<?php
namespace App\EventListener;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\KernelInterface;
class ApiExceptionListener
{
private bool $debug;
public function __construct(KernelInterface $kernel)
{
$this->debug = $kernel->isDebug();
}
public function onKernelException(ExceptionEvent $event): void
{
// if debug, symfony handles it
if ($this->debug) {
return;
}
$request = $event->getRequest();
// only for api requests
if (
$request->getRequestFormat() !== 'json' &&
!str_starts_with($request->getPathInfo(), '/api')
) {
return;
}
$exception = $event->getThrowable();
$status = $exception instanceof HttpExceptionInterface
? $exception->getStatusCode()
: 500;
$responseData = [
'title' => 'An error occurred',
'status' => $statusCode,
'detail' => $exception->getMessage(),
'class' => get_class($exception),
];
$event->setResponse(new JsonResponse($responseData, $status));
}
}