正在ExceptionListener中获取路由选项


Getting route options inside ExceptionListener

我正在开发一个ExceptionListener,对于一些控制器,我希望将错误格式化为json响应。我想我应该在@Route注释中定义一个选项,然后在ExceptionListener:中使用它

/**
 * @Route("/route/path", name="route_name", options={"response_type": "json"})
 */

和:

class ExceptionListener
{
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        // ...
    }
}

但是CCD_ 2不包含任何关于匹配路由的信息。有没有办法在ExceptionListener中获取options数组?

谢谢。

您应该能够使用从属性请求中检索路由名称

$request = $event->getRequest();
$routeName = $request->attributes->get('_route');

然后,如果将router服务注入到类中,则可以使用获得路由的实例

$route = $this->router->getRouteCollection()->get($routeName);

最后

$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'];
    }
}