Spring 如何从@ControllerAdvice类返回ModelAndView对象?
我试图处理来自SpringMVC控制器的异常,但我有一个问题 我的句柄返回ModelAndView对象,但Spring不使用它 在调试时,我看到Spring在浏览器中打开了带有标准Spring错误消息的页面,然后运行GlobalControllerExceptionHandler中的方法。为什么它在进入控制器之前不先调用该方法 我有以下代码:Spring 如何从@ControllerAdvice类返回ModelAndView对象?,spring,spring-mvc,Spring,Spring Mvc,我试图处理来自SpringMVC控制器的异常,但我有一个问题 我的句柄返回ModelAndView对象,但Spring不使用它 在调试时,我看到Spring在浏览器中打开了带有标准Spring错误消息的页面,然后运行GlobalControllerExceptionHandler中的方法。为什么它在进入控制器之前不先调用该方法 我有以下代码: @Slf4j @ControllerAdvice(annotations = Controller.class) public class GlobalC
@Slf4j
@ControllerAdvice(annotations = Controller.class)
public class GlobalControllerExceptionHandler {
@ExceptionHandler(Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) {
log.warn("Enter to handle method");
ModelAndView mav = new ModelAndView("exception");
mav.addObject("errorType", "errorType.toString()");
mav.addObject("exception", "rootCause");
mav.addObject("message", e.getMessage());
return mav;
}
}
问题可能在控制器中 您的
GlobalControllerExceptionHandler
类是正确的
例如:
@Slf4j
@ControllerAdvice
public class GlobalControllerExceptionHandler {
@ExceptionHandler(Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e){
log.warn("Enter to handle method");
ModelAndView modelAndView = new ModelAndView();
mav.addObject("errorType", "errorType.toString()");
modelAndView.addObject("exception", "rootCause");
modelAndView.addObject("message", e.getMessage());
modelAndView.setViewName("exception");
return modelAndView;
}
}
@Controller
public class ExampleController {
@GetMapping("/get/{someVariable}")
public String getMethod(@PathVariable("someVariable") int someVariable) throws Exception {
if(condition){
// code
} else {
throw new Exception(someVariable); // this will be caught by the GlobalControllerExceptionHandler's defaultErrorHandler
}
return "default";
}
}
我希望这会对你有所帮助。今天,它突然起作用了。我使用application.properties中的以下设置解决了此问题:
server.error.whitelabel.enabled=false
spring.mvc.throw-exception-if-no-handler-found=true
server.error.include-exception=true
server.error.path=
我还创建了一个error.html文件,如果ExceptionHandler中没有捕获到错误,thymeleaf将使用该文件(我不知道为什么…)不,不是。我有一个大的应用程序,它会抛出很多错误。控制器中怎么会出现问题?我怎样才能错误地抛出错误?对不起,英语不好。