📜 ⬆️ ⬇️

Symfony2 interceptor of exceptions using services or how to avoid using Event Listener

Today I want to share my humble experience and show how you can make an exception interceptor without using the Event Listener. But first, a few words about why this is needed.

I believe that using Event Listeners in a regular application makes the code confusing, and besides, many inexperienced developers misuse this approach (he did it himself). But the use of services makes the code understandable, since they are called in the place in which they are declared. And as you already understood, then it will be about services.

So, let's begin.

First, override ExceptionController, which is modestly hinted at by the official documentation :
')
namespace AppBundle\Controller; use Symfony\Bundle\TwigBundle\Controller\ExceptionController as Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpKernel\Exception\FlattenException; use Symfony\Component\HttpKernel\Log\DebugLoggerInterface; use AppBundle\Exception\ExceptionHandler; class ExceptionController extends Controller { public function __construct(ExceptionHandler $handler) { $this->handler = $handler; } public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null) { $message = $this->handler->handle($exception)->getMessage(); return new JsonResponse(array( 'message' => $message )); } } 

Next, create a service that handles exceptions:

 namespace AppBundle\Exception; use Symfony\Component\Security\Core\Exception\AccessDeniedException; class ExceptionHandler { private $message = null; public function handle($exception) { switch($exception->getClass()) { case 'Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException' : $this->message = "Need full authentication"; break; case 'Symfony\Component\Security\Core\Exception\AccessDeniedException': $this->message = "Access Denied"; break; /** *       **/ default: break; } return $this; } public function getMessage() { return $this->message; } } 

Now we register our service:

 # services.yml app_bundle.exception.handler: class: AppBundle\Exception\ExceptionHandler 

Next, we register our controller as a service (do not forget to pass an Exception Handler to it):

 # services.yml app_bundle.exception.controller: class: AppBundle\Controller\ExceptionController arguments: - @app_bundle.exception.handler 

It remains the most important thing: to specify in config.yml that our controller handles exceptions:

 # config.yml # Twig Configuration twig: exception_controller: app_bundle.exception.controller:showAction 

I hope for your constructive criticism, and also that this article will be useful for someone.

Source: https://habr.com/ru/post/276155/


All Articles