我正在尝试为异常注册一个监听器,但它永远不会被调用,这是我的代码:
app.yml:
services:
kernel.listener.exception_listener:
class: Appointmed\ApiBundle\EventListener\AppointmedExceptionEventListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
的Acme / ApiBundle /事件监听/ AcmeExceptionEventListener.php
<?php
/**
* Created by PhpStorm.
* User: danielrodriguez
* Date: 28/02/14
* Time: 19:14
*/
namespace Acme\ApiBundle\EventListener;
use JMS\Serializer\Serializer;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class AcmeExceptionEventListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
// You get the exception object from the received event
$exception = $event->getException();
$status = new Status($exception->getCode(), $exception->getMessage());
// Customize your response object to display the exception details
$response = new Response();
$serializer = SerializerBuilder::create()->build();
$response->setContent($serializer->serialize(array("status" => $status), 'json'));
$response->sendHeaders(array("ContentType" => "application/json"));
// 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(Response::HTTP_INTERNAL_SERVER_ERROR);
}
// Send the modified response object to the event
$event->setResponse($response);
}
}
每当我在控制器中抛出异常时,它都不会通过监听器,不知道发生了什么。
我可以意识到的一件事是,如果我故意将config.yml中的类更改为不存在的类,那么一切都是一样的。 e.g。
services:
kernel.listener.exception_listener:
class: Appointmed\ApiBundle\EventListener\asdf
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
答案 0 :(得分:0)
在服务定义中,您将类名称指定为“AppointmedExceptionEventListener”。
但是你编写的那个类是命名空间中的AcmeExceptionEventListener ACME \ ApiBundle \事件监听。如果您解决了这个问题,那么它应该按预期工作。