java - Spring boot 2.1.4 ControllerAdvice 不起作用

标签 java spring spring-boot exception

我无法完成此异常处理工作。我看起来类似的问题/答案,但没有一个有效。我有这门课 @ControllerAdvice处理应用程序级别的错误处理。这不是 REST 应用程序。这是 Spring boot 和 Thymeleaf

@EnableWebMvc
@ControllerAdvice
public class ErrorController {

    @ExceptionHandler(LoginFailureException.class)
    public ModelAndView handleLoginFailureException(LoginFailureException exception) {
        log.info("Handle LoginFailureException");
        return getModelAndView(exception.getMessage(), "user/login");
    }

    // other exception handling methods

    private ModelAndView getModelAndView(String message, String viewName) {
        ModelAndView mav = new ModelAndView();
        FlashMessage flashMessage = new FlashMessage();
        flashMessage.setType("danger");
        flashMessage.setMessage(message);
        mav.getModel().put("flashMessage", flashMessage);
        mav.setViewName(viewName);
        return mav;
    }

}

在我的WebSecurityConfigurerAdapter扩展课,我有这个

.failureHandler(loginFailureHandler)

LoginFailureHandler类看起来像这样:

@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    private MessageSource messageSource;

    @Autowired
    public LoginFailureHandler(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        throw new LoginFailureException(
                messageSource.getMessage("email.password.not.match", null, Locale.getDefault()));
    }
}

当我尝试使用无效的用户名登录时,我的应用程序崩溃并抛出此异常,并且永远不会到达 ExceptionHandler 方法。

com.company.application.controller.exception.LoginFailureException: Email or Username is not valid
    at com.company.application.security.LoginFailureHandler.onAuthenticationFailure(LoginFailureHandler.java:34) ~[classes/:na]

最佳答案

@ControllerAdvice 仅当从 @Controller 抛出异常时才会被命中,而不是 @Component

由于您正在使用危险/闪现消息“装饰”您的登录页面,因此您可能必须将请求转发到新的“页面”(例如user/loginerror) >) 代替?

关于java - Spring boot 2.1.4 ControllerAdvice 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55969194/

相关文章:

java - HttpServletRequest - API REST

java - 如何使用调度程序触发 Spring Quartz 触发器

java - Spring Boot Google SQL 无法正常工作

Java Spring 5 Get 和 findById mongo MonoOnErrorResume

java - 如何从多个字符串中解析文本?

Gradle 中的 Java 8 构建错误

配置的大小小于 min-response-size 的 Spring Boot gzip 压缩响应

java - xercesJ for XSD 1.1 : Validator correctly processes assertions, SAXParser 显然没有

java - 为什么这个 Spring 测试试图 Autowiring 它不应该看到的 bean?

java - 在 Sleuth 日志中看不到 TraceId 和 spanId