<?php
namespace AppBundle\EventListener;
use AppBundle\Exception\CustomValidationException;
use AppBundle\Exception\InvalidInputException;
use AppBundle\Exception\NotAllowedException;
use AppBundle\Exception\ResourceNotFoundException;
use AppBundle\Services\ApiDataCollectorService;
use Pimcore\Log\Simple;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
class ExceptionListener
{
const HTTP_INVALID_PARAMETERS = 400;
const HTTP_NOT_ALLOWED = 403;
const HTTP_RESOURCE_NOT_FOUND = 404;
const HTTP_ERROR_STATUS = 500;
const ROUTE_IDENTIFIER = 'api-v1';
/**
* @param ExceptionEvent $event
*/
public function onKernelException(ExceptionEvent $event)
{
$pathInfo = $event->getRequest()->getPathInfo();
if (strpos($pathInfo, static::ROUTE_IDENTIFIER) > 0) {
$exception = $event->getThrowable();
$event->allowCustomResponseCode();
Simple::log('api-error', $pathInfo . ' : ' . $exception->getMessage() . PHP_EOL . $exception->getTraceAsString());
$requestContent = $event->getRequest()->getContent();
if(is_string($requestContent)){
Simple::log('api-error', 'request : ' . $requestContent );
}
if(!empty(ApiDataCollectorService::getData())){
Simple::log('api-error', 'response : ' . json_encode(ApiDataCollectorService::getData()) );
}
switch (true) {
case $exception instanceOf NotAllowedException:
$event->setResponse(new JsonResponse([
'success' => false,
'message' => $exception->getMessage(),
'errorFields' => ApiDataCollectorService::getData(),
'errorType' => self::HTTP_NOT_ALLOWED,
]));
break;
case $exception instanceOf ResourceNotFoundException:
$event->setResponse(new JsonResponse([
'success' => false,
'message' => $exception->getMessage(),
'errorFields' => ApiDataCollectorService::getData(),
'errorType' => self::HTTP_RESOURCE_NOT_FOUND,
]));
break;
case $exception instanceOf InvalidInputException:
case $exception instanceOf CustomValidationException:
$event->setResponse(new JsonResponse([
'success' => false,
'message' => $exception->getMessage(),
'errorFields' => ApiDataCollectorService::getData(),
'errorType' => self::HTTP_INVALID_PARAMETERS,
]));
break;
default:
$event->setResponse(new JsonResponse([
'success' => false,
'message' => $exception->getMessage(),
'errorFields' => ApiDataCollectorService::getData(),
'errorType' => self::HTTP_ERROR_STATUS,
]));
break;
}
}
}
}