tir*_*hen 10 php events exception-handling symfony
我正在尝试创建一个侦听器,用于侦听403,404和500个异常.这适用于403和404例外但不适用于500例外.对于500个异常(或将作为客户端的500个错误返回的异常),永远不会调用onKernelException方法.它在我当前的Symfony项目中似乎是相同的,并且代码被添加到干净的Symfony 2.4.1安装中.
然后我通过执行不存在的函数引入500错误.
在开发环境中,我得到一个Symfony生成的页面,上面写着"哎呀,看起来像是出了问题." 然后查看有关抛出的"UndefinedFunctionException"以及500状态代码的信息.
在生产环境中,我得到一个空页面以及500状态代码.在错误日志prod.log中,我得到一个带有堆栈跟踪的"PHP致命错误:调用未定义函数"错误.
既然Symfony明显捕获了这个错误,为什么我不能用kernel.exception监听器捕获相应的异常呢?
我正在使用的课程是:
<?php
namespace SystemBundle\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
/**
* This exception listener will listen to 500, 404, and 403 errors and render a corresponding view
*
* @SuppressWarnings("static")
* @SuppressWarnings("else")
*/
class ExceptionListener
{
protected $templating;
protected $kernel;
public function __construct(EngineInterface $templating, $kernel)
{
$this->templating = $templating;
$this->kernel = $kernel;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$container = $this->kernel->getContainer();
// Exception object
$exception = $event->getException();
// Create Response object
$response = new Response();
// Get view name
$viewName = $container->getParameter('theme') . ':Exception:exception.html.twig';
if (!$this->templating->exists($viewName)) {
$viewName = 'AckebrinkChallengerSystemBundle:Exception:exception.html.twig';
}
// Set response content
$response->setContent($this->templating->render($viewName, array('exception' => $exception)));
// HttpExceptionInterface is a special type of exception that
// holds status code and header details
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
} else {
$response->setStatusCode(500);
}
// set the new $response object to the $event
$event->setResponse($response);
}
}
Run Code Online (Sandbox Code Playgroud)
我使用的服务配置是:
services:
kernel.listener.system_exception_listener:
class: SystemBundle\Listener\ExceptionListener
arguments:
- @templating
- @kernel
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
Run Code Online (Sandbox Code Playgroud)
小智 1
首先,确保您清除了 Prod 缓存。
其次,查看 Web 服务器中是否有某些内容为您捕获错误,即 Nginx 中的 fastcgi_intercept_errors,但这不太可能发生。
第三,尝试抛出异常而不是调用未声明的函数。
第四,在异常监听器中尽早尝试 $event->setResponse 以确保处理程序本身没有错误。
除此之外,我不知道。代码看起来没问题。您是否尝试过使用 XDebug 来查看代码的流程?
| 归档时间: |
|
| 查看次数: |
2355 次 |
| 最近记录: |