springboot统一异常处理
创建全局异常处理类:通过使用@ControllerAdvice定义统一的异常处理类,@ExceptionHandler用来定义针对的异常类型
1.增加异常类:
@ControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e)
throws Exception {
ModelAndView mav = new ModelAndView();
mav.addObject("msg", "异常咯...");
mav.setViewName("error");
return mav;
}
}
2.增加Controller方法,抛出异常:
@RequestMapping("/exception")
public String hello() throws Exception {
throw new Exception("发生错误");
}
3.src/main/resources/templates增加error.html:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>统一异常处理</title>
</head>
<body>
<h1>Error</h1>
<div th:text="${msg}"></div>
</body>
</html>
更多springboot相关知识参见[持续更新]
springboot教程目录
还没有评论,来说两句吧...