ToB企服应用市场:ToB评测及商务社交产业平台

标题: SpringBoot(八) - 统一数据返回,统一分页工具,统一异常处理 [打印本页]

作者: 九天猎人    时间: 2022-10-19 15:32
标题: SpringBoot(八) - 统一数据返回,统一分页工具,统一异常处理
1、统一数据返回

使用逆向工程来进行测试,实体,mapper等省略;
1.1 直接使用 RequestResoult

1.1.1 RequestResoult 请求结果返回实体
  1. //统一返回 实体 类
  2. @Data
  3. public class RequestResult<T> {
  4.     //状态码
  5.     private String code;
  6.     //状态说明,对code的说明
  7.     private String msg;
  8.     //接口数据
  9.     private T data;
  10. }
复制代码
1.1.2 service层

1.1.2.1 接口
  1. public interface EdocEntryService {
  2.     //按摘要查询
  3.     List<EdocEntry> getEdocEntriesBySummary(String summary);
  4.    
  5. }
复制代码
1.1.2.2 实现类

注意记得在 主启动类中添加 mapper接口扫描注解 :@MapperScan("com.kgc.sbt.mapper")
  1. @Service
  2. public class EdocEntryServiceImpl implements EdocEntryService {
  3.     @Autowired(required = false)
  4.     private EdocEntryMapper edocEntryMapper;
  5.     @Override
  6.     public List<EdocEntry> getEdocEntriesBySummary(String summary) {
  7.         //使用逆向工程,封装查询条件
  8.         EdocEntryExample edocEntryExample = new EdocEntryExample();
  9.         //排序条件
  10.         edocEntryExample.setOrderByClause(" id desc ");
  11.         //根据摘要 模糊查询
  12.         edocEntryExample.createCriteria().andSummaryLike("%" + summary + "%");
  13.         //调用持久层 查询数据
  14.         return edocEntryMapper.selectByExample(edocEntryExample);
  15.     }
  16.    
  17. }
复制代码
1.1.3 测试请求
  1. @Slf4j
  2. @RestController
  3. public class EdocEntryController {
  4.     @Autowired
  5.     private EdocEntryService edocEntrieService;
  6.     //根据电子文档,查询文档列表,直接使用 RequestResult
  7.     @GetMapping("/edocEntries")
  8.     //指定请求返回类型 RequestResult<List<EdocEntry>>
  9.         //public RequestResult<List<EdocEntry>> edocEntries(@RequestParam(required = false) String summary){
  10.     //自适应请求返回类型 RequestResult<?>
  11.     public RequestResult<?> edocEntries(@RequestParam(required = false) String summary){
  12.         
  13.         //调用业务接口,获取文档列表,进行统一返回
  14.         //创建统一返回对象
  15.         //每次都需要创建返回对象,代码冗余,不利于维护
  16.         RequestResult<List<EdocEntry>> requestResult = new RequestResult<>();
  17.         requestResult.setCode("200");
  18.         requestResult.setMsg("success");
  19.         List<EdocEntry> edocEntriesBySummary = edocEntrieService.getEdocEntriesBySummary(summary);
  20.         log.info("{}",edocEntriesBySummary);
  21.         requestResult.setData(edocEntriesBySummary);
  22.         //接口统一返回查询结果
  23.         return requestResult;
  24.         
  25.     }
  26. }
复制代码
测试结果:

1.2 使用 ResultBuildUtil 结果对象构建工具

1.2.1 CommonConstant 常量类
  1. //Description: 系统常量类,统一管理项目中所有的常量
  2. public class CommonConstant {
  3.     /*
  4.      统一返回成功的状态码
  5.      */
  6.     public static final String UNIFY_RESULT_SUCCESS_CODE = "200";
  7.     /*
  8.      统一返回成功的信息
  9.      */
  10.     public static final String UNIFY_RESULT_SUCCESS_MSG = "SUCCESS";
  11.     /*
  12.    统一返回错误的状态码
  13.    */
  14.     public static final String UNIFY_RESULT_FAIL_CODE = "999";
  15.     /*
  16.      统一返回错误的信息
  17.      */
  18.     public static final String UNIFY_RESULT_FAIL_MSG = "FAIL";
  19.     /*
  20.         分页默认页吗
  21.      */
  22.     public static final int DEFAULT_INIT_PAGE_NO = 1;
  23.     /*
  24.         分页默认条数
  25.      */
  26.     public static final int DEFAULT_INIT_PAGE_SIZE = 3;
  27. }
复制代码
1.2.2 ResultBuildUtil结果对象构建工具列
  1. //Description: 结果构建工具类
  2. public class ResultBuildUtil {
  3.     //构建成功返回,支持任意类型参数
  4.     public static <T> RequestResult<T> success(T t) {
  5.         //创建统一返回成功结果对象
  6.         RequestResult<T> requestResult = new RequestResult<>();
  7.         requestResult.setCode(CommonConstant.UNIFY_RESULT_SUCCESS_CODE);
  8.         requestResult.setMsg(CommonConstant.UNIFY_RESULT_SUCCESS_MSG);
  9.         requestResult.setData(t);
  10.         return requestResult;
  11.     }
  12.     //构建成功返回,空参
  13.     public static <T> RequestResult<T> success() {
  14.         return success(null);
  15.     }
  16.     //构建 失败返回,支持任意类型参数,用户不便于归类的异常错误结果返回
  17.     public static <T> RequestResult<T> fail(T t) {
  18.         //创建统一返回失败结果对象
  19.         RequestResult<T> requestResult = new RequestResult<>();
  20.         requestResult.setCode(CommonConstant.UNIFY_RESULT_FAIL_CODE);
  21.         requestResult.setMsg(CommonConstant.UNIFY_RESULT_FAIL_MSG);
  22.         requestResult.setData(t);
  23.         return requestResult;
  24.     }
  25.     //构建 失败返回,空参
  26.     public static <T> RequestResult<T> fail() {
  27.         //创建统一返回失败结果对象
  28.         return fail(null);
  29.     }
  30.     //构建 失败返回,自定义错误码,和说明,支持任意类型参数
  31.     public static <T> RequestResult<T> fail(String errCode,String errMsg,T t) {
  32.         //创建统一返回失败结果对象
  33.         RequestResult<T> requestResult = new RequestResult<>();
  34.         requestResult.setCode(errCode);
  35.         requestResult.setMsg(errMsg);
  36.         requestResult.setData(t);
  37.         return requestResult;
  38.     }
  39.     //构建 失败返回,自定义错误码,和说明,无参
  40.     public static <T> RequestResult<T> fail(String errCode,String errMsg) {
  41.         //创建统一返回 失败结果对象
  42.         RequestResult<T> requestResult = new RequestResult<>();
  43.         requestResult.setCode(errCode);
  44.         requestResult.setMsg(errMsg);
  45.         return requestResult;
  46.     }
  47. }
复制代码
1.2.3 service层

service层不变;
1.2.4 请求测试
  1. @Slf4j
  2. @RestController
  3. public class EdocEntryController {
  4.     @Autowired
  5.     private EdocEntryService edocEntrieService;
  6.     //根据电子文档,查询文档列表, 使用结果构建工具
  7.     @GetMapping("/edocEntries")
  8.     public RequestResult<?> edocEntries(@RequestParam(required = false) String summary){
  9.         //使用结果构建工具,返回成功的结果
  10.         return ResultBuildUtil.success(edocEntrieService.getEdocEntriesBySummary(summary));
  11.     }
  12. }
复制代码
测试结果:

2、统一分页工具

2.1 PageSupport 统一分页工具类
  1. // 分页 结果返回类
  2. @Data
  3. public class  PageSupport<T> {
  4.     //当前页码
  5.     private int pageNo;
  6.     //页面条数
  7.     private int pageSize;
  8.    //总条数
  9.     private int totalCount;
  10.     //总页数
  11.     private int totalPage;
  12.     //分页数据
  13.     private Collection<T> PageData;
  14.     //当总条数确定时,总条数确定
  15.     public void setTotalCount(int totalCount) {
  16.         this.totalCount = totalCount;
  17.         totalPage = totalCount % this.pageSize == 0
  18.                 ? totalCount / this.pageSize
  19.                 : totalCount / this.pageSize + 1;
  20.     }
  21. }
复制代码
2.2 service 层

2.2.1 接口
  1. public interface EdocEntryService {
  2.     //条件分页查询
  3.     PageSupport<EdocEntry> getEdocEntriesBySummary(String summary,Integer pageNo,Integer pageSize);
  4.    
  5. }
复制代码
2.2.2  实现类
  1. @Service
  2. public class EdocEntryServiceImpl implements EdocEntryService {
  3.     @Override
  4.     public PageSupport<EdocEntry> getEdocEntriesBySummary(String summary, Integer pageNo, Integer pageSize) {
  5.         //创建统一返回分页对象
  6.         PageSupport<EdocEntry> pageSupport = new PageSupport<>();
  7.         //设置分页参数
  8.         pageSupport.setPageNo(pageNo < 1 ? CommonConstant.DEFAULT_INIT_PAGE_NO : pageNo);
  9.         pageSupport.setPageSize(pageNo < 3 ? CommonConstant.DEFAULT_INIT_PAGE_SIZE : pageSize);
  10.         //封装查询条件
  11.         EdocEntryExample edocEntryExample = new EdocEntryExample();
  12.         //排序条件
  13.         edocEntryExample.setOrderByClause(" id desc ");
  14.         //根据摘要 模糊查询
  15.         edocEntryExample.createCriteria().andSummaryLike("%" + summary + "%");
  16.         // 查询满足条件总条数
  17.         pageSupport.setTotalCount((int) edocEntryMapper.countByExample(edocEntryExample));
  18.         //增加分页参数
  19.         edocEntryExample.setOffset((long)(pageSupport.getPageNo()-1)*pageSupport.getPageSize());
  20.         edocEntryExample.setLimit(pageSupport.getPageSize());
  21.         //增加分页数据
  22.         pageSupport.setPageData(edocEntryMapper.selectByExample(edocEntryExample));
  23.         //返回分页对象
  24.         return pageSupport;
  25.     }
  26.   
  27. }
复制代码
2.3 commons-lang中  isEmpty 方法和idBlank区别

2.3.1 依赖
  1. <dependency>
  2.     <groupId>commons-lang</groupId>
  3.     <artifactId>commons-lang</artifactId>
  4.     <version>2.6</version>
  5. </dependency>
复制代码
2.3.2  isEmpty 方法和idBlank区别
  1. isEmpty 和 isBlank ,isEmpty 方法和idBlank区别:只包含空格字符串判断,isEmpty是false,isBlank是true;
复制代码
2.3.2.1 isEmpty
  1. * <pre>
  2. * StringUtils.isEmpty(null)      = true
  3. * StringUtils.isEmpty("")        = true
  4. * StringUtils.isEmpty(" ")       = false
  5. * StringUtils.isEmpty("bob")     = false
  6. * StringUtils.isEmpty("  bob  ") = false
  7. * </pre>
复制代码
2.3.2.2 isBlank
  1. * <pre>
  2. * StringUtils.isBlank(null)      = true
  3. * StringUtils.isBlank("")        = true
  4. * StringUtils.isBlank(" ")       = true
  5. * StringUtils.isBlank("bob")     = false
  6. * StringUtils.isBlank("  bob  ") = false
  7. * </pre>
复制代码
2.4 测试请求
  1. //根据电子文档,查询文档列表
  2. @GetMapping("/edocEntriesPage")
  3. public RequestResult<?> edocEntriesPage(@RequestParam(value = "summary",required = false) String summary,
  4.                                         @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
  5.                                         @RequestParam(value = "pageSize",defaultValue = "3") Integer pageSize){
  6.     if(StringUtils.isBlank(summary)){
  7.         return ResultBuildUtil.fail();
  8.     }
  9.     //调用业务接口,获取文档列表,进行统一返回
  10.     //使用结果构建工具,返回成功的结果
  11.     return ResultBuildUtil.success(edocEntrieService.getEdocEntriesBySummary(summary,pageNo,pageSize));
  12.    
  13. }
复制代码
测试结果:

3、统一异常处理

3.1 EdocExceptionEnum 自定义异常枚举
  1. //自定义异常枚举
  2. public enum EdocExceptionEnum {
  3.     /**
  4.      * 参数为空
  5.      */
  6.     EDOC_REQUEST_PARAM_EMPTY("201", "参数为空"),
  7.     /**
  8.      * 参数为非法
  9.      */
  10.     EDOC_REQUEST_PARAM_ILLEGAL("202", "参数非法"),
  11.     /**
  12.      * 网络异常
  13.      */
  14.     EDOC_NETWORK_ERROR("301", "网络异常"),
  15.     /**
  16.      * 数据库异常
  17.      */
  18.     EDOC_DATABASE_ERROR("401", "数据库异常"),
  19.     /**
  20.      * 数据库异常
  21.      */
  22.     EDOC_SYSTEM_ERROR("501", "系统异常");
  23.     /**
  24.      * 异常码
  25.      */
  26.     private String errCode;
  27.     /**
  28.      * 异常说明
  29.      */
  30.     private String errMsg;
  31.     /**
  32.      * 提供带有两个参数的构造方法
  33.      */
  34.     EdocExceptionEnum(String errCode, String errMsg){
  35.         this.errCode = errCode;
  36.         this.errMsg = errMsg;
  37.     }
  38.     public String getErrCode() {
  39.         return errCode;
  40.     }
  41.     public String getErrMsg() {
  42.         return errMsg;
  43.     }
  44. }
复制代码
3.2  EdocException 自定义异常类
  1. public class EdocException extends RuntimeException{
  2.     /*
  3.         异常枚举类型全局私有属性
  4.     */
  5.     private EdocExceptionEnum edocExceptionEnum;
  6.     //继承 RuntimeException  生成所有的构造方法
  7.     public EdocException() {
  8.     }
  9.     public EdocException(String message) {
  10.         super(message);
  11.     }
  12.     public EdocException(String message, Throwable cause) {
  13.         super(message, cause);
  14.     }
  15.     public EdocException(Throwable cause) {
  16.         super(cause);
  17.     }
  18.     public EdocException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
  19.         super(message, cause, enableSuppression, writableStackTrace);
  20.     }
  21.     //自定义枚举异常构造函数
  22.     public EdocException(EdocExceptionEnum edocExceptionEnum){
  23.         this.edocExceptionEnum = edocExceptionEnum;
  24.     }
  25.     //获取枚举异常属性
  26.     public EdocExceptionEnum getEdocExceptionEnum() {
  27.         return edocExceptionEnum;
  28.     }
  29. }
复制代码
3.3 EdocExceptionHandler 自定义异常统一处理类
  1. //自定义异常统一处理类
  2. @ControllerAdvice
  3. public class EdocExceptionHandler {
  4.     /**
  5.      * @author : huayu
  6.      * @date   : 19/10/2022
  7.      * @param  : [edocException]
  8.      * @return : requestResoult<?>
  9.      * @description : 系统自定义异常处理,对系统中所有抛出自定义的异常,都会进行统一拦截处理,实现统一返回
  10.      */
  11.     @ExceptionHandler(EdocException.class)  //指定对该自定义异常类 进行处理
  12.     @ResponseBody  //指定返回的数据 为 json类型
  13.     public RequestResult<?> handleEdocException(EdocException edocException){
  14.         //统一返回失败的结果(前提:抛出的必须是带枚举类型的异常)
  15.         return ResultBuildUtil.fail(edocException.getEdocExceptionEnum().getErrCode(),edocException.getEdocExceptionEnum().getErrMsg());
  16.     }
  17. }
复制代码
3.4 请求测试
  1. @GetMapping("/edocEntriesPage")
  2. public RequestResult<?> edocEntriesPage(@RequestParam(value = "summary",required = false) String summary,
  3.                                         @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
  4.                                         @RequestParam(value = "pageSize",defaultValue = "3") Integer pageSize){
  5.         //判断 summary参数是否为空
  6.     if(StringUtils.isBlank(summary)){
  7.         //抛出自定义异常:使用异常枚举
  8.         throw new EdocException(EdocExceptionEnum.EDOC_REQUEST_PARAM_EMPTY);
  9.     }
  10.     ////抛出自定义异常:使用异常枚举
  11.     try {
  12.         return ResultBuildUtil.success(edocEntrieService.getEdocEntriesBySummary(summary,pageNo,pageSize));
  13.     } catch (Exception e) {
  14.         //e.printStackTrace();
  15.          //抛出自定义异常:使用异常枚举
  16.         throw new EdocException(EdocExceptionEnum.EDOC_DATABASE_ERROR);
  17.     }
  18. }
复制代码
测试请求参数为空:

测试数据库密码错误:





免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4