• springboot做统一格式返回


    1. message类。确定返回格式
    package com.dbhd.gvs.common.result;
    
    import org.springframework.http.HttpStatus;
    
    public class Message<T> {
        String status;
        //向前端返回的内容
        String message;
    
        T data;
    
        public Message() {
        }
    
        public Message(String status, String message) {
            this.status = status;
            this.message = message;
        }
    
        public Message(String status, String message, T data) {
            this.data = data;
            this.status = status;
            this.message = message;
        }
    
        public static <T> Message<T> custom(String status, String message, T data) {
            return new Message(status, message, data);
        }
    
        public static <T> Message<T> custom(String status, String message) {
            return new Message(status, message);
        }
    
        public static HttpStatus num2HttpStatus(String code) {
            HttpStatus status = HttpStatus.NOT_FOUND;
            for (HttpStatus httpStatus : HttpStatus.values()) {
                boolean b = Integer.parseInt(code) == httpStatus.value();
                if (b) {
                    return httpStatus;
                }
            }
            return status;
        }
    
        public String getStatus() {
            return status;
        }
    
        public void setStatus(String status) {
            this.status = status;
        }
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
        public T getData() {
            return data;
        }
    
        public void setData(T data) {
            this.data = data;
        }
    }
    
    1. ResultVo统一返回格式
    package com.dbhd.gvs.common.result;
    
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    
    /**
     * 统一返回格式,错误处理
     *
     * @param <T>
     */
    public class ResultVo<T> extends ResponseEntity<Message> {
    
        public ResultVo(HttpStatus status) {
            super(status);
        }
    
        public ResultVo(String code, String msg) {
            super(Message.custom(code, msg), Message.num2HttpStatus(code));
        }
    
        public ResultVo(String code, String msg, T data) {
            super(Message.custom(code, msg, data), Message.num2HttpStatus(code));
        }
    
        public static <T> ResultVo<T> success(T data) {
            return new ResultVo("200", "成功", data);
        }
    
        public static <T> ResultVo<T> saveSuccess(T data) {
            return new ResultVo("201", "添加成功", data);
        }
    
        public static <T> ResultVo<T> failed(T data) {
            return new ResultVo("422", "失败", data);
        }
    
        public static <T> ResultVo<T> failMsg(String msg) {
            return new ResultVo("422", msg);
        }
    
        public static <T> ResultVo<T> custom(String code, String msg, T data) {
            return new ResultVo(code, msg, data);
        }
    
        public static <T> ResultVo<T> custom(String code, String msg) {
            return new ResultVo(code, msg);
        }
    
    }
    
    1. 不同错误处理,以BadRequestException举例
    package com.dbhd.gvs.common.exception;
    
    import lombok.Data;
    import lombok.EqualsAndHashCode;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @ResponseBody
    @Data
    @EqualsAndHashCode(callSuper = true)
    public class BadRequestException extends Exception{
    
        public BadRequestException(String msg) {
            this.msg = msg;
        }
    
        private final String code = "400";
        private String msg;
    }
    

    MyControllerAdvide类处理错误类:

    package com.dbhd.gvs.common.exception;
    
    import com.dbhd.gvs.common.result.ResultVo;
    import org.springframework.http.HttpStatus;
    import org.springframework.validation.BindException;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.FieldError;
    import org.springframework.web.bind.MethodArgumentNotValidException;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseStatus;
    import org.springframework.web.bind.annotation.RestControllerAdvice;
    
    import java.util.Objects;
    
    @RestControllerAdvice
    public class MyControllerAdvice {
    
        /**
         * 自定义捕捉异常
         * @param ex
         * @return
         */
        @ExceptionHandler(CustomException.class)
        public ResultVo myErrorHandler(CustomException ex) {
            return ResultVo.custom(ex.getCode(), ex.getMsg());
        }
    
        /**
         *
         * @param ex
         * @return
         */
        @ExceptionHandler(NotFoundException.class)
        public ResultVo NotFoundException(NotFoundException ex) {
            return ResultVo.custom(ex.getCode(), ex.getMsg());
        }
    
        @ExceptionHandler(BadRequestException.class)
        public ResultVo BadRequestException(BadRequestException ex) {
            return ResultVo.custom(ex.getCode(), ex.getMsg());
        }
    
        /**
         * validator注解校验返回 拦截表单参数校验
         * @param ex
         * @return
         */
        @ResponseStatus(HttpStatus.OK)
        @ExceptionHandler({BindException.class})
        public ResultVo bindException(BindException ex) {
            System.out.println("--bindException---");
            BindingResult bindingResult = ex.getBindingResult();
            return ResultVo.custom("400", Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
    
        /**
         * validator注解校验返回 拦截JSON参数校验
         * @param ex
         * @return
         */
        @ResponseStatus(HttpStatus.OK)
        @ExceptionHandler(MethodArgumentNotValidException.class)
        public ResultVo bindException(MethodArgumentNotValidException ex) {
            System.out.println("----拦截JSON参数校验-----");
            BindingResult bindingResult = ex.getBindingResult();
            StringBuilder errorMessage = new StringBuilder(bindingResult.getFieldErrors().size() * 16);
    //        errorMessage.append("Invalid Request:");
            for (int i = 0; i < bindingResult.getFieldErrors().size(); i++) {
                if (i > 0) {
                    errorMessage.append(", ");
                }
                FieldError fieldError = bindingResult.getFieldErrors().get(i);
                errorMessage.append(fieldError.getField());
                errorMessage.append(": ");
                errorMessage.append(fieldError.getDefaultMessage());
            }
            return ResultVo.custom("400", errorMessage.toString());
        }
    
    }
    

    controller使用:

    public class CoordinateController {
    
        @Autowired
        CoordinateService coordinateService;
    
        @GetMapping
        @ApiOperation("所有坐标列表")
        public ResultVo get() throws Exception {
            List<Coordinate> list = coordinateService.getList();
            return ResultVo.success(list);
        }
    
    

    serveice使用错误处理:

        @Override
        public Coordinate update(CoordinateDto dto) throws NotFoundException {
            Coordinate coordinate = coordinateDao.getById(dto.getCoordinateId());
            if (coordinate == null) {
                throw new NotFoundException("坐标不存在,可以先添加");
            }
            coordinate.setCoordinate(dto.getCoordinate());
            coordinateDao.update(coordinate);
            return coordinate;
        }
    
  • 相关阅读:
    「2013-8-5」企业基因
    HashMap和ConcurrentHashMap详解
    JVM 详解
    Dubbo 项目学习(四) 接口抽取以及依赖版本统一
    Dubbo 项目学习(三) 消费Dubbo服务
    Dubbo 项目学习(二) 发布Dubbo服务
    Spring Boot 日志问题记录
    Dubbo 项目学习(一) Admin 管理控制台
    Idea 搭建 SSM 项目框架
    Idea 搭建 SSH 项目框架
  • 原文地址:https://www.cnblogs.com/liangyy/p/16093125.html
Copyright © 2020-2023  润新知