如何在生产时避免在Symfony2中显示堆栈跟踪?

时间:2017-09-21 08:59:27

标签: symfony

当没有必要角色的用户尝试访问需要更高令牌的页面时,我理所当然地获得

  

AccessDeniedHttpException:令牌没有所需的角色

但接下来是整个堆栈跟踪,包括文件路径。 E.g。

  

'文件' => string' /var/www/myApp/vendor/jms/security-extra-bundle/JMS/SecurityExtraBundle/Security/Authorization/Interception/MethodSecurityInterceptor.php'

如何删除调试信息?

我已经确定我正在生产(app.php)和那个

$kernel = new AppKernel('prod', false);

更新

要根据Robert的答案完成解决方案,我必须调整yml语法以包含短划线

services:
    core.exceptlistener:
        class:  UserBundle\Listener\ExceptionListener
        arguments: ['@service_container', '@templating']
        tags:
            - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

然后在onKernelException中指定的位置创建twig文件,确保该文件继承了项目其余部分的基本树枝

1 个答案:

答案 0 :(得分:1)

REG:为避免堆栈跟踪,您可以使用事件监听器

听众类

<?php
namespace UserBundle\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Twig\Template;

/**
 * Created by PhpStorm.
 * User: robert
 * Date: 20/8/17
 * Time: 2:26 PM
 */
class ExceptionListener
{
    /**
     *
     * @var ContainerInterface
     */
    private $container;

    function __construct($container) {
        $this->container = $container;
    }
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        // We get the exception object from the received event
        $exception = $event->getException();
        $response = new Response($this->container->get('templating')->renderResponse('UserBundle:Exception:error403.html.twig',
            array('exception'=>$exception->getMessage())));

        $event->setResponse($response);
    }

}

在您的services.yml

services:
        core.exceptlistener:
            class:  UserBundle\Listener\ExceptionListener
            arguments: ['@service_container', '@templating']
            tags:
                { name: kernel.event_listener, event: kernel.exception, method: onKernelException }