<?php
namespace Seidemann\Hanagud\EventSubscriber;
use Seidemann\Hanagud\Http\ApiResponse;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\ExceptionDataCollector;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Profiler\Profiler;
use Throwable;
class ApiExceptionSubscriber implements EventSubscriberInterface
{
public function __construct(private ?Profiler $profiler = null)
{
}
/**
* Creates the ApiResponse from any Exception.
*/
private function createApiResponse(Throwable $exception): ApiResponse
{
$statusCode = $exception instanceof HttpExceptionInterface
? $exception->getStatusCode()
: Response::HTTP_INTERNAL_SERVER_ERROR;
return new ApiResponse(null, $exception, $statusCode);
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
$request = $event->getRequest();
if (in_array('application/json', $request->getAcceptableContentTypes())) {
$response = $this->createApiResponse($exception);
$event->setResponse($response);
// If profiler is enabled, log exception into it
if (null !== $this->profiler) {
$exceptionCollector = $this->profiler->get('exception');
/* @var ExceptionDataCollector $exceptionCollector */
$exceptionCollector->collect($request, $response, $exception);
}
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::EXCEPTION => [
['onKernelException', -9],
],
];
}
}