我正在为一个网站构建一个管理面板,我想更改发生 404 异常时调用的 View 但仅限管理应用程序。 (路径:/admin/*)
我已经过度使用了网站的 error404.html.twig
View (位于 app/Resources/TwigBundle/views/Exception/
)。
我想到了 kernel.exception 事件监听器,但现在我遇到了两件事:
仅当路由以前缀:
/admin/
开头时才加载另一个错误 View$route = $event->getRequest->get('_route')->render() //returns NULL
调用
$event->container->get('templated')->render()
函数。
由于脚本失败,我最终陷入无限循环(空白页)。
我唯一要做的事情是:
检索异常代码:
$exception = $event->getException(); $code = $exception->getCode();
创建新响应:
$response = new Response(); $event->setResponse($response);
关于如何实现这一目标有什么建议吗?
[编辑]
类(class):
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/
*/
}
}
还有 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 }
最佳答案
出于某种原因,这有效:
// 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);
}
这基本上就是我之前使用不同语法所做的事情......
@dmirkitanov 无论如何,感谢您的帮助!
关于exception - Symfony2 - 操纵来自内核异常监听器的请求/响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7465751/