<?php
namespace App\EventListener;
use App\Model\Out\ExceptionOut;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\JsonResponse;
class AppExceptionSubscriber implements EventSubscriberInterface
{
/**
* @var string
*/
private $env;
public function __construct(string $env)
{
$this->env = $env;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$path = explode('/', $event->getRequest()->getPathInfo());
if ($path[1] !== 'api') return;
$out = new ExceptionOut($event->getException(), $this->env);
$response = new JsonResponse($out);
$response->headers->set('Content-Type', 'application/problem+json');
$event->setResponse($response);
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::EXCEPTION => 'onKernelException'
);
}
}