<?php
namespace App\SupplierApiBundle\EventListener;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
class ExceptionListener
{
/**
* @var string
*/
private $host;
/**
* ExceptionListener constructor.
*
* @param string $host
*/
public function __construct(string $host)
{
$this->host = $host;
}
/**
* @param GetResponseForExceptionEvent $event
*/
public function onKernelException(ExceptionEvent $event)
{
$request = $event->getRequest();
if ($request->getHost() === $this->host) {
$response = $this->createApiResponse($event->getThrowable());
$event->setResponse($response);
}
}
/**
* Creates the ApiResponse from any Exception
*
* @param \Exception $exception
*
* @return JsonResponse
*/
private function createApiResponse(\Throwable $exception)
{
$statusCode = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : Response::HTTP_INTERNAL_SERVER_ERROR;
return new JsonResponse([
'code' => $statusCode,
//'message' => $statusCode === 500 ? null : $this->getMessage( $exception )
'message' => $this->getMessage($exception)
], $statusCode);
}
private function getMessage(\Throwable $exception): string
{
if (! empty($exception->getMessage())) {
return $exception->getMessage();
}
if ($exception instanceof NotFoundHttpException) {
return 'Not found';
}
if ($exception instanceof AccessDeniedHttpException) {
return 'Access denied';
}
return 'Unknown error';
}
}