不能使用AuthenticationException的子类

时间:2012-10-06 19:55:48

标签: java exception java-ee exception-handling spring-security

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

public class RegistrationNotCompleteException extends AuthenticationException {
    public RegistrationNotCompleteException(String msg) {
        super(msg);
    }
}

在我的loadUserByUsername课程的UserDetailsService中,我进行了以下检查:

if (!user.getHasRegistered()) {
    System.out.println("######## User: " + username
        + " has not completed the registration");
    throw new RegistrationNotCompleteException(
        "User has not completed registration");
}

因此用户将按预期转发到AuthenticationFailureHandler类。

但是当试图在onAuthenticationFailure方法中获取异常类时如下:

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

请告知如何做到这一点。

1 个答案:

答案 0 :(得分:0)

通过将支票更改为exception.getCause().getClass()而不是exception.getClass()

来解决