定义公共异常

    1. @Data
    2. public class BaseException extends Exception{
    3. private int code;
    4. private String msg;
    5. public BaseException() {
    6. super();
    7. this.code = 99999;
    8. this.msg = "服务异常,请联系开发人员";
    9. }
    10. public BaseException(int code, String msg) {
    11. super();
    12. this.code = code;
    13. this.msg = msg;
    14. }
    15. }
    16. public class VerificationCodeException extends BaseException{
    17. private VerificationCodeException() {
    18. super(100001, "验证码错误");
    19. }
    20. public static VerificationCodeException throwVerificationCodeException() {
    21. return new VerificationCodeException();
    22. }
    23. }

    异常控制器

    1. @ControllerAdvice
    2. public class ExceptionController {
    3. @ExceptionHandler({ BaseException.class }) // 当发生BaseException类(及其子类)的异常时,进入该方法
    4. public ModelAndView baseExceptionHandler(BaseException e) {
    5. ModelAndView mv = new ModelAndView();
    6. mv.addObject("code", e.getCode());
    7. mv.addObject("message", e.getMessage());
    8. mv.setViewName("myerror");// 跳转到resource/templates/myerror.html页面
    9. return mv;
    10. }
    11. @ExceptionHandler({ Exception.class }) // 当发生Exception类的异常时,进入该方法
    12. public ModelAndView exceptionHandler(Exception e) {
    13. ModelAndView mv = new ModelAndView();
    14. mv.addObject("code", 99999);// 其他异常统一编码为99999
    15. mv.addObject("message", e.getMessage());
    16. mv.setViewName("myerror");// 跳转到resource/templates/myerror.html页面
    17. return mv;
    18. }
    19. }

    @ControllerAdvice> @RestControllerAdvice

    区别也就是 和 Controller 和 RestCOntroller 一样


    前端页面**

    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>error</title>
    6. </head>
    7. <body>
    8. <div>服务异常</div>
    9. 错误码:
    10. <span th:text="${code}"></span>
    11. 错误信息:
    12. <span th:text="${message}"></span>
    13. </body>
    14. </html>