Reputation: 242
i want to create a empty custom exception and exception listener that return json response for that every time i throw my custom exception automatically my exception listener first called and return new json response without any exception page
i tried this code but i see always exception page without json response
this is my listener:
class CustomExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if($exception instanceof TestException)
{
return new JsonResponse(['code'=>JsonResponse::HTTP_FORBIDDEN,'status'=>"missing api key!"],JsonResponse::HTTP_FORBIDDEN);
}
}
}
exception:
class TestException extends RuntimeException
{
}
and this is my usage:
if (!in_array($token, $this->apiKeys)) {
throw new TestException();
}
Upvotes: 1
Views: 1199
Reputation: 12103
If you only return some new response from that handler, nothing happens. You have to replace the response that is currently in use in the event the following way:
<?php
class CustomExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof TestException) {
$response = new JsonResponse(['code' => JsonResponse::HTTP_FORBIDDEN, 'status' => "missing api key!"], JsonResponse::HTTP_FORBIDDEN);
$event->setResponse($response);
}
}
}
A possible source for this is the Symfony documentation itself at https://symfony.com/doc/current/event_dispatcher.html. The reason for this behaviour is that Symfony registers multiple handlers for that event, for example to write exceptions to a log. One of these parts ensures that a response is stored within the event, and later in the process the response is extracted from the event to be sent to the client (mainly by \Symfony\Component\HttpKernel\HttpKernel::handleException
).
The event is passed from listener to listener to keep track of multiple modifications, as the event itself holds more metadata than only the response.
Upvotes: 2