美文网首页
spring boot 统一错误返回

spring boot 统一错误返回

作者: Epat | 来源:发表于2022-03-31 10:29 被阅读0次

    在后端服务中,我们常常会遇到各种异常错误,这时我们就需要有一个统一的错误处理来处理这些异常,并返回一个统一的数据给到前端
    首先我们实现一个统一返回实体类和对应的工具类

    1. BaseResponseVo 返回实体类
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class BaseResponseVo {
    
        // 状态码
        private Integer code;
        // 内容
        private Object data;
    
        // 信息
        private String message;
    
    }
    
    1. ResponseTool 返回工具类
    public class ResponseTool {
    
        public static BaseResponseVo success () {
            BaseResponseVo baseResponseVo = new BaseResponseVo();
            baseResponseVo.setCode(HttpStatus.OK.value());
            return baseResponseVo;
        }
    
        public static BaseResponseVo success (Object data) {
            BaseResponseVo baseResponseVo = new BaseResponseVo();
            baseResponseVo.setCode(HttpStatus.OK.value());
            baseResponseVo.setData(data);
            return baseResponseVo;
        }
    
        public static BaseResponseVo success (Object data, String message) {
            BaseResponseVo baseResponseVo = new BaseResponseVo();
            baseResponseVo.setCode(HttpStatus.OK.value());
            baseResponseVo.setData(data);
            baseResponseVo.setMessage(message);
            return baseResponseVo;
        }
    
        public static BaseResponseVo error () {
            BaseResponseVo baseResponseVo = new BaseResponseVo();
            baseResponseVo.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return baseResponseVo;
        }
    
        public static BaseResponseVo error (Object data) {
            BaseResponseVo baseResponseVo = new BaseResponseVo();
            baseResponseVo.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            baseResponseVo.setData(data);
            return baseResponseVo;
        }
    
        public static BaseResponseVo error (Object data, String message) {
            BaseResponseVo baseResponseVo = new BaseResponseVo();
            baseResponseVo.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            baseResponseVo.setData(data);
            baseResponseVo.setMessage(message);
            return baseResponseVo;
        }
    
        public static void makeResponse(HttpServletResponse response, BaseResponseVo baseResponseVo) throws IOException {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(baseResponseVo.getCode());
            response.getOutputStream().write(JSONObject.toJSONString(baseResponseVo,
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.QuoteFieldNames).getBytes());
        }
    
    }
    
    1. 默认提示注解
    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ApiOperation {
        String value();
    }
    
    1. 统一错误处理类
    @Slf4j
    @RestControllerAdvice
    public class GlobalExceptionHandler {
    
        @Autowired
        RequestMappingHandlerMapping requestMappingHandlerMapping;
    
        /**
         * 处理所有不可知的异常
         */
        @ExceptionHandler(Exception.class)
        public ResponseEntity<ApiError> handleException(Exception e, HttpServletRequest request){
            // 打印堆栈信息
            log.error("系统错误", e);
            try {
                HandlerExecutionChain handlerExecutionChain = requestMappingHandlerMapping.getHandler(request);
                HandlerMethod handlerMethod = (HandlerMethod)handlerExecutionChain.getHandler();
                Method method = handlerMethod.getMethod();
                ApiOperation apiOperation  = method.getAnnotation(ApiOperation.class);
                String result = apiOperation.value() + "错误";
                return new ResponseEntity(ResponseTool.error(result), HttpStatus.INTERNAL_SERVER_ERROR);
            } catch (Exception ex) {
                log.error("获取controller方法异常", ex);
                return new ResponseEntity(ResponseTool.error("系统错误"), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
    }
    
    1. 使用
    @GetMapping
    @ApiOperation("查询信息")
    public ResponseEntity<Object> list(GbxxlhQueryCriteria criteria, Pageable pageable) {
      throw new RuntimeException("异常");
    }
    

    相关文章

      网友评论

          本文标题:spring boot 统一错误返回

          本文链接:https://www.haomeiwen.com/subject/dowgjrtx.html