PHP / Symfony – 为什么使用Twig呈现的控制器的异常仅未在生产
发布时间:2020-12-13 17:00:15 所属栏目:PHP教程 来源:网络整理
导读:我有2个控制器动作,一个通过渲染(控制器(…))函数在另一个的树枝模板中渲染.如果我在子动作中抛出一个异常,它只会在DEV模式下捕获,而不是在PRODuction中,任何想法为什么以及如何绕过它? DefaultController.php /** * @Route("/test/child",name="test_child
我有2个控制器动作,一个通过渲染(控制器(…))函数在另一个的树枝模板中渲染.如果我在子动作中抛出一个异常,它只会在DEV模式下捕获,而不是在PRODuction中,任何想法为什么以及如何绕过它?
DefaultController.php /** * @Route("/test/child",name="test_child") */ public function childAction(Request $request) { throw new Exception($request->getRequestUri()); return $this->render("child.html.twig"); } /** * @Route("/test/parent",name="test_parent") */ public function parentAction(Request $request) { try { return $this->render("parent.html.twig"); } catch(Exception $e) { die("got it!"); } } child.html.twig Child parent.html.twig Parent <br> {{ render(controller("WebBundle:Pages:child")) }} 结果: 解决方法
在Symfony2项目中,Twig在生产模式下默认捕获异常.
您可以对其进行配置,以便在开发模式下抛出所有异常: // app/config/config.yml twig: # ... debug: true # default: %kernel.debug% 或者,配置异常监听器: 服务声明: // app/config/services.yml app.exception_listener: class: AcmeCoreBundleListenerExceptionListener arguments: [ "@templating" ] tags: - { name: kernel.event_listener,event: kernel.exception,method: onKernelException } 类: use SymfonyComponentHttpFoundationResponse; use SymfonyComponentHttpKernelEventGetResponseForExceptionEvent; use SymfonyComponentTemplatingEngineInterface; class ExceptionListener { private $templateEngine; public function __construct(EngineInterface $templateEngine) { $this->templateEngine = $templateEngine; } public function onKernelException(GetResponseForExceptionEvent $event) { $response = $this->templateEngine->render( 'TwigBundle:Exception:error500.html.twig',array('status_text' => $event->getException()->getMessage()) ); $event->setResponse(new Response($response)); } } 用于异常消息跟踪/消息显示的模板: // app/Resources/TwigBundle/views/Exception/error500.html.twig {% extends '::base.html.twig' %} {% block body %} <div class='error'> <div class="message"> <h2>Application Error</h2> <p>Oops! {{ status_text }}</p> </div> </div> {% endblock %} 编辑 要仅捕获特定异常,请在侦听器的开头添加以下内容: // Listen only on the expected exception if (!$event->getException() instanceof RedirectException) { return; } 希望这可以帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |