50 lines
1.4 KiB
PHP
50 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace App\EventSubscriber;
|
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
|
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
|
|
use Symfony\Component\HttpFoundation\JsonResponse;
|
|
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
|
use Symfony\Component\HttpFoundation\RequestStack;
|
|
use Symfony\Component\HttpKernel\KernelInterface;
|
|
|
|
readonly class ApiExceptionSubscriber implements EventSubscriberInterface
|
|
{
|
|
public function __construct(
|
|
private readonly RequestStack $requestStack,
|
|
private readonly KernelInterface $kernel,
|
|
)
|
|
{
|
|
}
|
|
|
|
public static function getSubscribedEvents(): array
|
|
{
|
|
return [
|
|
ExceptionEvent::class => 'onKernelException',
|
|
];
|
|
}
|
|
|
|
public function onKernelException(ExceptionEvent $event): void
|
|
{
|
|
if ($this->kernel->getEnvironment() === 'dev') {
|
|
return;
|
|
}
|
|
|
|
$exception = $event->getThrowable();
|
|
$statusCode = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 500;
|
|
$message = $exception->getMessage();
|
|
|
|
$data = [
|
|
'@context' => '/contexts/Error',
|
|
'@type' => 'hydra:Error',
|
|
'hydra:title' => 'An error occurred',
|
|
'hydra:description' => $message,
|
|
];
|
|
|
|
$response = new JsonResponse($data, $statusCode);
|
|
$event->setResponse($response);
|
|
}
|
|
|
|
}
|