<?php
namespace Jabber\RestApiBundle\EventListener;
use Jabber\RestApiBundle\Http\ApiResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExceptionListener
{
/**
* @param ExceptionEvent $event
*/
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
$request = $event->getRequest();
if (str_starts_with($request->getPathInfo(), "/api/")) {
$response = $this->createApiResponse($exception);
$event->setResponse($response);
}
}
/**
* Creates the ApiResponse from any Exception
*
* @param \Exception $exception
*
* @return ApiResponse
*/
private function createApiResponse(\Throwable $exception, $errors = [])
{
if ($exception instanceof HttpExceptionInterface) {
$statusCode = $exception->getStatusCode() ?? Response::HTTP_INTERNAL_SERVER_ERROR;
} else {
$statusCode = $exception->getCode() ?? Response::HTTP_INTERNAL_SERVER_ERROR;
}
if ($statusCode == 0) {
$statusCode = Response::HTTP_INTERNAL_SERVER_ERROR;
}
return new ApiResponse($exception->getMessage(), null, $errors, $statusCode);
}
}