LBr*_*dge 8 exception event-listener symfony
我正在为网站构建一个管理面板,我想更改发生404异常时调用的视图,但仅限于管理应用程序.(path: /admin/*)
我已经过度error404.html.twig了解app/Resources/TwigBundle/views/Exception/网站的观点(at ).
我想到了kernel.exception事件监听器,但现在我遇到了两件事:
仅当路由以前缀开头时才加载另一个错误视图: /admin/
$route = $event->getRequest->get('_route')->render()
//returns NULL
Run Code Online (Sandbox Code Playgroud)调用$event->container->get('templating')->render()函数.
当脚本失败时,我最终得到一个无限循环(空白页).
我唯一能做的就是:
检索异常代码:
$exception = $event->getException();
$code = $exception->getCode();
Run Code Online (Sandbox Code Playgroud)创建新响应:
$response = new Response();
$event->setResponse($response);
Run Code Online (Sandbox Code Playgroud)有关如何实现这一目标的任何建议?
班级:
namespace Cmt\AdminBundle\EventListener;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Bundle\TwigBundle\TwigEngine;
class AdminActionListener
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* @var TwigEngine
*/
protected $templating;
/**
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container, TwigEngine $templating){
// assign value(s)
$this->container = $container;
$this->templating = $templating;
}
/**
*
* @param GetResponseForExceptionEvent $event
*/
public function onKernelException(GetResponseForExceptionEvent $event)
{
// get exception
$exception = $event->getException();
// get path
$path = $event->getRequest()->getPathInfo();
/*
* Redirect response to new 404 error view only
* on path prefix /admin/
*/
}
}
Run Code Online (Sandbox Code Playgroud)
和services.yml:
services:
cmt_admin.exception.action_listener:
class: Cmt\AdminBundle\EventListener\AdminActionListener
arguments: [@service_container] [@templating]
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
Run Code Online (Sandbox Code Playgroud)
由于某种原因,这有效:
// get exception
$exception = $event->getException();
// get path
$path = $event->getRequest()->getPathInfo();
if ($exception->getStatusCode() == 404 && strpos($path, '/admin') === 0){
$templating = $this->container->get('templating');
$response = new Response($templating->render('CmtAdminBundle:Exception:error404.html.twig', array(
'exception' => $exception
)));
$event->setResponse($response);
}
Run Code Online (Sandbox Code Playgroud)
这基本上就是我之前使用不同语法所做的事情......
@dmirkitanov 无论如何,感谢您的帮助!
| 归档时间: |
|
| 查看次数: |
12356 次 |
| 最近记录: |