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 )); } }
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; } }
# services.yml app_bundle.exception.handler: class: AppBundle\Exception\ExceptionHandler
# services.yml app_bundle.exception.controller: class: AppBundle\Controller\ExceptionController arguments: - @app_bundle.exception.handler
# config.yml # Twig Configuration twig: exception_controller: app_bundle.exception.controller:showAction
Source: https://habr.com/ru/post/276155/
All Articles