<?php
namespace ApiBundle\Exceptions;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
/**
* Class JsonExceptionListener
* @package ApiBundle\Exceptions
*/
class JsonExceptionListener
{
const API_ROUTE = '/api';
/**
* @param GetResponseForExceptionEvent $event
* @return null
*/
public function onKernelException(GetResponseForExceptionEvent $event)
{
$path = $event->getRequest()->getPathInfo();
$isApiRoute = $this->isApiRoute($path);
if (!$isApiRoute) {
return null;
}
$exception = $event->getException();
$data = [
'message' => $exception->getMessage(),
];
$response = new JsonResponse($data);
$event->setResponse($response);
}
/**
* @param $path
* @return bool
*/
private function isApiRoute($path)
{
if (strpos($path, self::API_ROUTE) === 0) {
return true;
}
return false;
}
}