Skip to content

Instantly share code, notes, and snippets.

@BerezhniyDmitro
Created February 25, 2021 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BerezhniyDmitro/fcc685e6d33a521303957939ef0d4dd2 to your computer and use it in GitHub Desktop.
Save BerezhniyDmitro/fcc685e6d33a521303957939ef0d4dd2 to your computer and use it in GitHub Desktop.
<?php
namespace App\EventSubscriber;
use Exception;
use InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelInterface;
use Throwable;
/**
* Class DomainExceptionSubscriber - Подписчик реагирующий на экзепшены.
*/
final class DomainExceptionSubscriber implements EventSubscriberInterface
{
private LoggerInterface $logger;
private KernelInterface $kernel;
public function __construct(LoggerInterface $logger, KernelInterface $kernel)
{
$this->logger = $logger;
$this->kernel = $kernel;
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
if ($this->kernel->getEnvironment() === 'dev') {
return;
}
$response = $this->handleUnknownExceptions($exception);
if ($exception instanceof InvalidArgumentException) {
$response = $this->handleKnownExceptions($exception);
}
if ($exception instanceof NotFoundHttpException) {
$response = $this->handleNotFoundHttpExceptions();
}
$event->setResponse($response);
}
public static function getSubscribedEvents()
{
return [
'kernel.exception' => 'onKernelException',
];
}
private function handleKnownExceptions(Exception $exception): JsonResponse
{
$this->logger->warning($exception);
$message = $exception->getMessage();
return new JsonResponse(['errors' => [$message]], 422);
}
private function handleUnknownExceptions(Throwable $exception): JsonResponse
{
$this->logger->error($exception);
return new JsonResponse(['errors' => ['An unknown exception occurred.']], 500);
}
private function handleNotFoundHttpExceptions(): JsonResponse
{
return new JsonResponse(['errors' => ['Object not found']], 404);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment