zoukankan      html  css  js  c++  java
  • Spring|@ExceptionHandler

    捕获系统中未被catch的异常,统一返回给用户。

    自定义异常类:

    public class CdaException extends RuntimeException {
    
        private static final long serialVersionUID = 8461347797506225533L;
    
        public CdaException() {
        }
    
        public CdaException(String errorMsg) {
            super(errorMsg);
        }
    
        public CdaException(Exception ex){
            super(ex);
        }
    }

    统一异常处理:

    @ControllerAdvice
    @Component
    public class GlobalExceptionHandler {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
        /**
         * 判断错误是否是已定义的已知错误,不是则由未知错误代替,同时记录在log中
         *
         * @param ex 异常
         * @return 错误内容
         */
        @ExceptionHandler(value = Exception.class)
        @ResponseBody
        public Result exceptionGet(Exception ex, HttpServletRequest request) {
            LOGGER.error("【系统异常】请求uri:[{}]", request.getRequestURI(), ex);
    
            // 项目自定义异常
            if(ex instanceof CdaException){
                CdaException cdaException = (CdaException) ex;
                return ResultGenerator.genServerErrorResult(cdaException.getMessage());
            }
    
            //权限异常
    
            //...
    
            return ResultGenerator.genServerErrorResult(ex.getMessage());
        }
    }


    @ControllerAdvice、@RestControllerAdvice:Controller的增强注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping、@PostMapping、@GetMapping注解中。

  • 相关阅读:
    MySql-数据库基础
    Window安装MySQL
    Python程序中的进程操作-进程间通信(multiprocess.Queue)
    线程
    上传电影代码
    并发编程基础
    基于socketserver实现并发的socket编程
    模拟ssh远程执行命令
    GIT的使用,Pycharm中使用GitHub
    主机如何访问运行在虚拟机中的Django项目
  • 原文地址:https://www.cnblogs.com/maikucha/p/14043883.html
Copyright © 2011-2022 走看看