<?php
namespace App\EventSubscriber\Api;
use App\Helper\Api\JsonFormatter\Throwable\Formatter;
use App\Helper\Api\Translator\ApiTranslator;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Subscriber for kernel exception to handle most unexpected errors.
*
* @package API
* @internal
*/
class ExceptionSubscriber extends AbstractSubscriber
{
protected LoggerInterface $logger;
/**
* Returns an array of event names this subscriber wants to listen to.
*
* The array keys are event names and the value can be:
*
* * The method name to call (priority defaults to 0)
* * An array composed of the method name to call and the priority
* * An array of arrays composed of the method names to call and respective
* priorities, or 0 if unset
*
* For instance:
*
* * ['eventName' => 'methodName']
* * ['eventName' => ['methodName', $priority]]
* * ['eventName' => [['methodName1', $priority], ['methodName2']]]
*
* The code must not depend on runtime state as it will only be called at compile time.
* All logic depending on runtime state must be put into the individual methods handling the events.
*
* @noinspection PhpArrayShapeAttributeCanBeAddedInspection
* @noinspection PhpUnused
*/
public static function getSubscribedEvents(): array
{
// return the subscribed events, their methods and priorities
return [
KernelEvents::EXCEPTION => [
['onKernelException', 0]
]
];
}
/**
* Constructor.
*
* @param Formatter $formatter
* @param ApiTranslator $translator
* @param LoggerInterface $logger
*/
public function __construct(Formatter $formatter, ApiTranslator $translator, LoggerInterface $logger)
{
parent::__construct($formatter, $translator);
$this->logger = $logger;
}
/**
* Handles most unexpected backend API errors after kernel initialization and ensures a JSON response is given to
* the frontend.
*
* @param ExceptionEvent $event
* @return void
* @noinspection PhpUnused
*/
public function onKernelException(ExceptionEvent $event): void
{
// only handle for API routes
if (preg_match('/^\/api\/|^\/api$/', $event->getRequest()->getRequestUri())) {
$event->setResponse($this->formatter->format($event->getThrowable()));
$errorData = $this->formatter->getErrorData($event->getThrowable());
$message = $errorData->getHttpStatusCode() . ' ' . Response::$statusTexts[$errorData->getHttpStatusCode()];
if ($errorData->getHttpStatusCode() !== Response::HTTP_UNPROCESSABLE_ENTITY) {
$errorData->addData(["request-data" => $event->getRequest()->request->all()]);
}
$this->logger->error($message, $errorData->jsonSerialize());
}
}
}