Routing 如何在Symfony2.3中获取NotFoundException而不是MethodNotAllowedException?
我有一个控制器的方法,注释如下:Routing 如何在Symfony2.3中获取NotFoundException而不是MethodNotAllowedException?,routing,symfony-2.3,Routing,Symfony 2.3,我有一个控制器的方法,注释如下: /** * @Route("/document/remove/", name="document_remove", requirements={"id"="^\d+$"}, defaults={"_format"="json"}) * @Method({"DELETE"}) */ public function removeDocumentAction(Request $request) 如果我尝试在浏览器中打开“/document/remove/”ur
/**
* @Route("/document/remove/", name="document_remove", requirements={"id"="^\d+$"}, defaults={"_format"="json"})
* @Method({"DELETE"})
*/
public function removeDocumentAction(Request $request)
如果我尝试在浏览器中打开“/document/remove/”url(获取请求),我会看到
MethodNotAllowedException
。没错,但我想得到一个NotFoundException
。我如何才能做到这一点?您需要编写一个事件侦听器。您将订阅内核异常。检查异常是否为MethodNotAllowedException,然后将其转换为NotFoundException
//Your Event Listener
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
class ExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if (!($exception instanceof MethodNotAllowedException)) {
return;
}
$response = new Response($exception->getMessage(),404);
$event->setResponse($response);
}
}
查看有关如何创建和注册事件侦听器的