<?php
namespace App\EventListener;
use App\Utils\ExceptionCodes;
use ReflectionClass;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class ApiExceptionSubscriber implements EventSubscriberInterface
{
/**
* Handles the response of any "App" Exception, displaying error code and message depending on the debug policy.
* @param ExceptionEvent $event
*/
public function onKernelException(ExceptionEvent $event): void
{
$e = $event->getThrowable();
if (!$e instanceof HttpException) {
// not an App Exception: no treatment
return;
}
// retrieving all valid codes
$codes = (new ReflectionClass(ExceptionCodes::class))->getConstants();
$data = [
'error_code' => in_array((string) $e->getCode(), $codes) ? $e->getCode() : 0,
'error_status' => $e->getStatusCode(),
];
// message and trace are displayed only in DEBUG mode
if ($_ENV['APP_DEBUG']) {
$data['error_message'] = $e->getMessage();
$data['error_trace'] = $e->getTrace();
}
$response = new JsonResponse($data, $e->getStatusCode());
$response->headers->set('Content-Type', 'application/problem+json');
$event->setResponse($response);
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return array(
KernelEvents::EXCEPTION => 'onKernelException'
);
}
}