Java 无法使用AuthenticationException的子类

Java 无法使用AuthenticationException的子类,java,exception,jakarta-ee,exception-handling,spring-security,Java,Exception,Jakarta Ee,Exception Handling,Spring Security,我正在尝试创建AuthenticationException的异常子类,如下所示: public class RegistrationNotCompleteException extends AuthenticationException { public RegistrationNotCompleteException(String msg) { super(msg); } } public void onAuthenticationFailure(HttpS

我正在尝试创建AuthenticationException的异常子类,如下所示:

public class RegistrationNotCompleteException extends AuthenticationException {
    public RegistrationNotCompleteException(String msg) {
        super(msg);
    }
}
public void onAuthenticationFailure(HttpServletRequest request,
    HttpServletResponse response, AuthenticationException exception)
    throws IOException, ServletException {

    UsernamePasswordAuthenticationToken token =
        (UsernamePasswordAuthenticationToken) exception.getAuthentication();
    String username = token.getName();
    String credentials = token.getCredentials().toString();
    System.out.println("Exception class: " + exception.getClass());
在UserDetails服务类的loadUserByUsername中,我进行以下检查:

if (!user.getHasRegistered()) {
    System.out.println("######## User: " + username
        + " has not completed the registration");
    throw new RegistrationNotCompleteException(
        "User has not completed registration");
}
因此,用户将按预期转发到AuthenticationFailureHandler类

但当尝试在onAuthenticationFailure方法中获取异常类时,如下所示:

public class RegistrationNotCompleteException extends AuthenticationException {
    public RegistrationNotCompleteException(String msg) {
        super(msg);
    }
}
public void onAuthenticationFailure(HttpServletRequest request,
    HttpServletResponse response, AuthenticationException exception)
    throws IOException, ServletException {

    UsernamePasswordAuthenticationToken token =
        (UsernamePasswordAuthenticationToken) exception.getAuthentication();
    String username = token.getName();
    String credentials = token.getCredentials().toString();
    System.out.println("Exception class: " + exception.getClass());
它显示异常类是AuthenticationException而不是RegistrationNotCompleteException

我想验证异常类是RegistrationNotCompleteException


请给出建议。

通过将检查改为exception.getCause.getClass而不是exception来解决。getClass

通过将检查改为exception.getCause.getClass而不是exception来解决。getClass

好问题。但是我可以问你为什么要扩展身份验证例外吗?您似乎没有添加任何功能。@AlexR,我想创建一个新的异常RegistrationNotCompleteException作为标记,以便在AuthenticationFailureHandler@AlexR,有什么建议可以实现我想要的吗?好问题。但是我可以问你为什么要扩展身份验证例外吗?您似乎没有添加任何功能。@AlexR,我想创建一个新的异常RegistrationNotCompleteException作为标记,以便在AuthenticationFailureHandler@AlexR,有什么建议可以实现我想要的吗?@tcb,忘了接受它,因为你们应该在第二天接受答案。@tcb,忘了接受它,因为你应该接受第二天的答案。