我无法完成此异常处理工作。我看起来类似的问题/答案,但没有一个有效。我有这门课 @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/