Spring Boot 2.1.4 ControllerAdvice无法正常工作

时间:2019-05-03 11:47:02

标签: 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]

2 个答案:

答案 0 :(得分:0)

尝试将其添加到您的主spring boot应用程序中以关闭Error Mvc的自动配置  配置

@SpringBootApplication
@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
public class SpringBootDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoApplication.class, args);
    }
}

答案 1 :(得分:0)

@ControllerAdvice仅在从@Controller引发异常而不是@Component引发异常时被命中。

由于您要用危险/闪烁消息“修饰”登录页面,因此您可能不得不将request转发到新的“页面”(例如user/loginerror)上?