<?php
namespace App\EventListener;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ApiIframeExceptionListener
{
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
// Check if the request is coming from your REST API controllers
if (strpos($event->getRequest()->attributes->get('_route'),'api_iframe') !== false) {
// Handle exceptions for your API controllers
$response = $this->handleApiException($exception);
$event->setResponse($response);
}
}
private function handleApiException($exception)
{
$statusCode = ($exception instanceof HttpExceptionInterface) ? $exception->getStatusCode() : 500;
$response = [
'error' => [
'code' => $exception,
'message' => $exception->getMessage(),
],
];
return new JsonResponse($response, $statusCode);
}
}