Php 如何在我的LoginController中捕获UserProvider::refreshUser()引发的异常消息?

Php 如何在我的LoginController中捕获UserProvider::refreshUser()引发的异常消息?,php,symfony,authentication,symfony4,Php,Symfony,Authentication,Symfony4,我有一个应用程序,它使用稍微修改的AbstractFormLoginAuthenticator来提供身份验证,因此我有了自定义的\app\Security\UserProvider和\app\Security\Authenticator类。这些都是目前工作良好,我现在想添加一个新的功能。在UserProvider::refreshUser()方法中,我想添加一个可能立即使会话无效的检查。例如,可能用户记录有一个布尔活动字段,如果该字段在用户会话期间被切换为false,我想立即注销该用户。我有这样

我有一个应用程序,它使用稍微修改的
AbstractFormLoginAuthenticator
来提供身份验证,因此我有了自定义的
\app\Security\UserProvider
\app\Security\Authenticator
类。这些都是目前工作良好,我现在想添加一个新的功能。在
UserProvider::refreshUser()
方法中,我想添加一个可能立即使会话无效的检查。例如,可能用户记录有一个布尔
活动
字段,如果该字段在用户会话期间被切换为false,我想立即注销该用户。我有这样的想法:

public function refreshUser(UserInterface $user)
{
    if ($someCondition) {
        throw new UsernameNotFoundException('You have been logged out for reasons.');
    }
    return $user;
}
这可以根据需要工作——当用户发出新请求时,条件触发,身份验证被清除,用户立即重定向到登录控制器。然而,我有一个挥之不去的问题。我想向用户展示发生了什么。也就是说,用户应该看到,“您因各种原因而注销。”

但是,通过
AuthenticationUtils::getLastAuthenticationError()
方法引发的异常不可用,就像在
\App\Security\Authenticator
中引发的异常一样。因此,我似乎没有办法在控制器中获取消息文本并将其传递给视图

我尝试抛出
CustomUserMessageAuthenticationException
,但也没有传播。我已经检查了会话数据,并确认没有存储对异常的引用。我是否需要自己手动将其添加到会话中,然后在控制器中将其拉出?或者Symfony有一些我没有的内置机制

TL;DR如果我在验证器中抛出异常,我可以通过调用
getLastAuthenticationError()
从随后的登录控制器获取它。如何对我的UserProvider中抛出的异常执行相同的操作

[UPDATE]我可以通过使用
CustomUserMessageAuthenticationException
并使用
getLastAuthenticationError()
查找的密钥手动将其插入会话来实现我想要的:

public function refreshUser(UserInterface $user)
{
    if ($someCondition) {
        $e = new CustomUserMessageAuthenticationException('You have been logged out for reasons.');
        $this->session->set(Security::AUTHENTICATION_ERROR, $e);
        throw $e;
    }
    return $user;
}

我不确定这是否理想,如果有人有替代方案,我很乐意考虑。

您的验证器扩展了AbstractFormLoginAuthenticator,对吗?是否在验证器的getUser方法中调用refreshUser?是的,我的验证器扩展了AbstractFormLoginAuthenticator,但两者都没有显式调用refreshUser。