我无法获得此异常处理工作。我看起来类似的问题/答案,但没有一个起作用。我使用@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]
答案 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
)上?