关于SpringBoot的全局异常处理,其实十分简单。首先,要新建一个SpringBoot项目添加两个依赖,spring-boot-starter-web和spring-boot-starter-thymeleaf。
这个时候,我们便可以把异常信息展示在thymeleaf页面。
编写接口:
以往的SpringMVC配置在SpringBoot项目中依然生效。所以可以通过实现HandlerExceptionResolver接口或者添加@ExceptionHandler注解来处理全局异常。
@ControllerAdvice
public class GlobalExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
ModelAndView mv = new ModelAndView("01");
mv.addObject("error",ex.getMessage());
return mv;
}
}
@ControllerAdvice
public class GlobalExceptionHandler2 {
@ExceptionHandler(ArithmeticException.class)
public ModelAndView resolveException( Exception ex) {
ModelAndView mv = new ModelAndView("01");
mv.addObject("error",ex.getMessage());
return mv;
}
}
thymeleaf视图必须放在/resources/templates文件夹下,此时需要新建一个01.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试页面</title>
</head>
<body>
<h4>异常信息显示:&l