看看 symfony 中的默认异常监听器Symfony\Component\HttpKernel\EventListener\ExceptionListener
。
(1) 运行一个控制器可以这样实现:
$request = new \Symfony\Component\HttpFoundation\Request();
$request->setMethod('GET');
[..]
try {
$response = $event->getKernel()->handle($request, HttpKernelInterface::SUB_REQUEST, true);
} catch (\Exception $e) {
return; // pass it to next exception listener this way
}
$event->setResponse($response);
(2) 在异常监听器中渲染模板
您需要做的就是将模板(引擎)传递给 service.yml 中的侦听器
services:
foobar.exception_listener_service:
class: %foobar.exception_listener_service.class%
arguments:
container: "@service_container"
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 255 }
在侦听器中,您可以呈现如下所列的模板
$templating = $this->container->get('templating');
$response = new Response($templating->render('foobar:Exception:error404.html.twig', array('exception' => $exception)));
$event->setResponse($response);