Symfony生产环境错误页无法通过{{app.user}}获取登录用户求助
解决Symfony生产环境错误页无法获取{{app.user}}的问题
我之前也碰到过一模一样的情况,Symfony生产环境下的错误页默认确实不会自动携带用户登录信息——这是因为默认的错误控制器在生产模式下为了简化流程和安全考量,没有把Security上下文传递到模板渲染环节。下面给你两种经过验证的可行解决方案:
方案一:自定义错误控制器(推荐)
这种方式最直接可控,通过继承默认的错误控制器,手动把用户信息注入到模板变量中:
- 创建自定义错误控制器
在src/Controller/目录下新建CustomExceptionController.php,代码如下:
<?php namespace App\Controller; use Symfony\Bundle\TwigBundle\Controller\ExceptionController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Security; class CustomExceptionController extends ExceptionController { private Security $security; public function __construct(\Twig\Environment $twig, bool $debug, Security $security) { parent::__construct($twig, $debug); $this->security = $security; } public function showAction(Request $request, \Throwable $exception, string $format = 'html', int $code = 0): Response { // 获取当前登录用户 $user = $this->security->getUser(); // 调用父类方法获取基础响应模板参数 $templateVars = $this->getTemplateVars($request, $exception, $format, $code); // 注入用户信息到模板变量 $templateVars['app']['user'] = $user; // 重新渲染模板并返回响应 $content = $this->twig->render( $this->findTemplate($request, $format, $code, $this->debug), $templateVars ); $response = parent::showAction($request, $exception, $format, $code); $response->setContent($content); return $response; } }
- 修改框架配置指向自定义控制器
打开config/packages/framework.yaml,找到或添加error_controller配置:
framework: # ... 其他已有配置 error_controller: App\Controller\CustomExceptionController::showAction
- 清除生产环境缓存
执行命令更新缓存,确保配置生效:
php bin/console cache:clear --env=prod
方案二:使用事件监听器注入用户信息
如果你不想修改控制器,可以通过监听异常事件,把用户信息添加到请求属性中,再在模板里调用:
- 创建异常事件监听器
在src/EventListener/目录下新建ExceptionUserInjectorListener.php:
<?php namespace App\EventListener; use Symfony\Component\HttpKernel\Event\ExceptionEvent; use Symfony\Component\Security\Core\Security; class ExceptionUserInjectorListener { private Security $security; public function __construct(Security $security) { $this->security = $security; } public function onKernelException(ExceptionEvent $event): void { // 获取当前登录用户 $user = $this->security->getUser(); if ($user) { // 将用户信息存入请求属性,供模板调用 $event->getRequest()->attributes->set('logged_in_user', $user); } } }
- 注册监听器
打开config/services.yaml,添加监听器的服务标签配置:
services: # ... 其他已有服务 App\EventListener\ExceptionUserInjectorListener: tags: - { name: kernel.event_listener, event: kernel.exception }
修改错误模板
先把Symfony默认的错误模板复制到自定义目录(避免修改vendor文件被覆盖):复制vendor/symfony/twig-bundle/Resources/views/Exception/error.html.twig到templates/bundles/TwigBundle/Exception/下,然后修改模板中获取用户的代码,把{{ app.user }}替换为{{ app.request.attributes.get('logged_in_user') }}即可。清除生产缓存
同样执行缓存清除命令:
php bin/console cache:clear --env=prod
额外注意事项
- 确保自定义错误模板的路径正确,Symfony会优先读取
templates/bundles/下的自定义模板,而不是vendor里的默认模板。 - 在生产环境的错误页中,避免展示用户敏感信息,只保留必要的标识内容即可。
内容的提问来源于stack exchange,提问作者Parth Khatri
相关产品推荐
相关产品推荐

