Created
February 25, 2021 10:55
-
-
Save BerezhniyDmitro/fcc685e6d33a521303957939ef0d4dd2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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