定义公共异常
@Data
public class BaseException extends Exception{
private int code;
private String msg;
public BaseException() {
super();
this.code = 99999;
this.msg = "服务异常,请联系开发人员";
}
public BaseException(int code, String msg) {
super();
this.code = code;
this.msg = msg;
}
}
public class VerificationCodeException extends BaseException{
private VerificationCodeException() {
super(100001, "验证码错误");
}
public static VerificationCodeException throwVerificationCodeException() {
return new VerificationCodeException();
}
}
异常控制器
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler({ BaseException.class }) // 当发生BaseException类(及其子类)的异常时,进入该方法
public ModelAndView baseExceptionHandler(BaseException e) {
ModelAndView mv = new ModelAndView();
mv.addObject("code", e.getCode());
mv.addObject("message", e.getMessage());
mv.setViewName("myerror");// 跳转到resource/templates/myerror.html页面
return mv;
}
@ExceptionHandler({ Exception.class }) // 当发生Exception类的异常时,进入该方法
public ModelAndView exceptionHandler(Exception e) {
ModelAndView mv = new ModelAndView();
mv.addObject("code", 99999);// 其他异常统一编码为99999
mv.addObject("message", e.getMessage());
mv.setViewName("myerror");// 跳转到resource/templates/myerror.html页面
return mv;
}
}
@ControllerAdvice> @RestControllerAdvice
区别也就是 和 Controller 和 RestCOntroller 一样
前端页面**
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>error</title>
</head>
<body>
<div>服务异常</div>
错误码:
<span th:text="${code}"></span>
错误信息:
<span th:text="${message}"></span>
</body>
</html>