Reputation: 2618
I am working on an ExceptionListener and for some controllers I want errors to be formatted as json responses. I thought I would define an option in @Route
annotation and then use it in ExceptionListener:
/**
* @Route("/route/path", name="route_name", options={"response_type": "json"})
*/
and:
class ExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
// ...
}
}
but GetResponseForExceptionEvent
doesn't contain any info about matched route. Is there a way to get the options
array inside ExceptionListener?
thanks.
Upvotes: 1
Views: 864
Reputation: 36964
You should be able to retrieve the route name from the attribute request with
$request = $event->getRequest();
$routeName = $request->attributes->get('_route');
then, if you inject the router
service into your class, you can get the instance of the route with
$route = $this->router->getRouteCollection()->get($routeName);
finally
$options = $route->getOptions();
echo $options['response_type']
use Symfony\Component\Routing\RouterInterface;
class ExceptionListener
{
private $router;
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$request = $event->getRequest();
$route = $this->router->getRouteCollection()->get(
$request->attributes->get('_route')
);
$options = $route->getOptions();
// $options['response_type'];
}
}
Upvotes: 2