相关博客:SpringBoot 统一异常处理
第一步:创建项目 添加Maven依赖:
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-thymeleaf
nz.net.ultraq.thymeleaf
thymeleaf-layout-dialect
2.4.1
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
application.yml
server:
port: 80
servlet:
context-path: /wpe
spring:
thymeleaf:
#前缀,也就是模板存放的路径
prefix: classpath:/templates/
#编码格式
encoding: UTF-8
check-template-location: false
#关闭缓存,不然无法看到实时页面
cache: false
#后缀
suffix: .html
#设置不严格的html
mode: HTML
servlet:
content-type: text/html
第二步:自定义异常
CustomException.java:
public class CustomException extends RuntimeException {
// 异常错误编码
private Integer code;
// 异常信息
private String msg;
private CustomException() {
}
public CustomException(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
ModelAndViewException.java
public class ModelAndViewException extends RuntimeException {
// 异常错误编码
private Integer code;
// 异常信息
private String msg;
private ModelAndViewException() {
}
public static ModelAndViewException transfer(CustomException e) {
return new ModelAndViewException(e.getCode(), e.getMessage());
}
private ModelAndViewException(int code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
第三步:自定义异常处理器
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(ModelAndViewException.class)
public ModelAndView viewExceptionHandler(HttpServletRequest req, ModelAndViewException e) {
ModelAndView modelAndView = new ModelAndView();
//将异常信息设置如modelAndView
modelAndView.addObject("exception", e);
modelAndView.addObject("url", req.getRequestURL());
modelAndView.setViewName("error");
//返回ModelAndView
return modelAndView;
}
}
第四步:自定义注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface ModelAndView {
}
第五步:创建Controller
@Controller
@RequestMapping("/mave")
@Slf4j
public class ModelAndViewExceptionController {
/**
* 模拟系统异常
*/
@ModelAndView
@GetMapping("/fun1")
public String fun1() {
try {
Class.forName("com.mysql.jdbc.xxxx.Driver");
} catch (ClassNotFoundException e) {
throw new CustomException(400,"在XXX业务,ff1()方法内,出现ClassNotFoundException");
}
return "index";
}
}
第六步:在resources/templates目录下创建error.html
错误页面
error
第七步:启动项目,结果: