How to get NotFoundException instead of MethodNotAllowedException in Symfony2.3?

StackOverflow https://stackoverflow.com/questions/22554322

  •  18-06-2023
  •  | 
  •  

문제

I have a controller's method annotated like this:

/**
 * @Route("/document/remove/", name="document_remove", requirements={"id"="^\d+$"}, defaults={"_format"="json"})
 * @Method({"DELETE"})
 */
public function removeDocumentAction(Request $request)

If I try to open "/document/remove/" url in my browser (GET request), I see MethodNotAllowedException. That is right, but I want to get a NotFoundException instead. How can I do this?

도움이 되었습니까?

해결책

You will need to write an event listener. You are going to subscribe to the kernel exception. Check if the exception is a MethodNotAllowedException and then translate it to a 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);
    }
}

Have a look at the Symfony Documentation on how to create and register your event listener.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top