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 拦截什么异常类 后面的是自定义异常类

  • 相关阅读:
    029- 位运算符
    028- 三目运算符
    027- 字符串链接运算符
    026- 布尔运算符
    lucene 结合数据库做搜索
    JDK 1.8判断集合种的元素是否存在相同
    Springboot 集成jpa使用
    json 的使用 Java对象转json
    Java 短信发送
    1 eclipse 离线安装activiti插件
  • 原文地址:https://www.cnblogs.com/zhangzhiping35/p/14049714.html
Copyright © 2011-2022 走看看