zoukankan      html  css  js  c++  java
  • 全局拦截自定义的异常

    • 添加一个自定义的异常类MyException继承Exception
    public class BusinessException extends Exception {
        private int code;
        private String massage;
    
        public BusinessException(int code,String message) {
            this.massage = message;
            this.code = code;
        }
    
        public int getCode() {
            return code;
        }
    
        public void setCode(int code) {
            this.code = code;
        }
    
        public String getMassage() {
            return massage;
        }
    
        public void setMassage(String massage) {
            this.massage = massage;
        }
    }
    • 添加一个全局的异常处理器处理异常
    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
        /**
         * http 417 期望失败
         * code 1003 认证数量须为在模板的限定范围
         */
        @ExceptionHandler(BusinessException.class)
        public ResponseEntity<?> BusinessExceptionHandler(BusinessException e){
            CommonUtils.errorLog(e,logger);//打印异常信息
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new Error(new Date(), e.getCode(), e.getMessage()));
        }
    }
    • 在需要抛异常的地方throw一下
        @ResponseBody
        @GetMapping("product/page")
        public PageModel<Product> productPage(PageModel pageModel) throws BusinessException {
            System.out.println(123);
            if(true){
                throw new BusinessException(909,"myException");
            }
            return productService.findAll(pageModel);
        }
  • 相关阅读:
    团队展示
    平衡二叉树AVLTree
    红黑树原理
    日本楼市崩盘始末
    池化
    Spring配置多数据源
    关于C语言指针几个容易混淆的概念
    .net core 部署 Docker 所遇到的几个问题
    自定义类加载器也是无法实现加载java.lang.String的
    jquery轻量级数字动画插件jquery.countup.js
  • 原文地址:https://www.cnblogs.com/erfsfj-dbc/p/11756477.html
Copyright © 2011-2022 走看看