Commit ece7f1a1 by Lech Sawon

api error handling

parent 02547a82
<?php
declare(strict_types=1);
namespace App\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
final class ApiExceptionSubscriber implements EventSubscriberInterface
{
private RequestStack $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::EXCEPTION => [
['processException', 10],
['logException', 0],
]
];
}
public function processException(ExceptionEvent $event)
{
$request = $this->requestStack->getCurrentRequest();
if ($request && false === strpos($request->getRequestUri(), 'api')) {
return;
}
$exception = $event->getThrowable();
if ($exception instanceof \Throwable) {
$response = new JsonResponse(
[
'message' => 'Server Error'
],
500
);
$event->setResponse($response);
}
if ($exception instanceof NotFoundHttpException) {
$response = new JsonResponse(
[
'message' => 'Entity not found'
],
404
);
$event->setResponse($response);
}
}
public function logException(ExceptionEvent $event) {
//@TODO
// np używając logger Interface
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment