zoukankan      html  css  js  c++  java
  • java全局异常捕捉处理

    @RestControllerAdvice(annotations = RestController.class)
    @Slf4j
    public class GlobalExceptionHandler {
    
        /**
         * 全局异常捕捉处理
         * @param ex
         * @return
         */
        @ExceptionHandler(value = Exception.class)
        @ResponseBody
        public DataResponse<Boolean> errorHandler(HttpServletRequest req, Exception ex) {
            Map map = new HashMap();
            map.put("code", 500);
            map.put("ex",ex);
            map.put("message", ex.getMessage());
            map.put("url", req.getRequestURL());
            log.error("发生异常:{}",JSON.toJSONString(map));
            return DataResponse.builderFailed(ex.getMessage());
        }
    
    }
    

      

    @RestControllerAdvice(annotations = RestController.class)
    @Slf4j
    public class GlobalExceptionInterceptor {
    
        /**
         * 捕获自定义异常,返回json信息
         */
        @ExceptionHandler({MamchargeException.class})
        @ResponseBody
        public ResultVO errorHandle(MamchargeException e) throws Exception {
            return new ResultVO(null,e.getErrorCode(),e.getMsg());
        }
    
        @ExceptionHandler({Exception.class})
        @ResponseBody
        public ResultVO errorHandle(Exception e) throws Exception {
            log.error("系统出错:",e);
            return ResultVO.isFail();
        }
    }

    RestControllerAdvice 注解表示拦截那一层

    ExceptionHandler 拦截什么异常类 后面的是自定义异常类

  • 相关阅读:
    机电传动控制第五周学习笔记
    机电传动控制第四周学习笔记和仿真作业
    第三周学习笔记
    《机电传动控制》第二周作业
    学习笔记第一周
    第十周作业
    第八周仿真作业
    第六周学习笔记
    第五周作业
    机电传动控制第四周作业
  • 原文地址:https://www.cnblogs.com/zhangzhiping35/p/14049714.html
Copyright © 2011-2022 走看看