好处

现在公司开发基本上都是以前后分离模式为主,所以要有个统一的数据格式,这样有什么好处呢?

  • 能够提高前后端对接的效率(特别重要)
  • 代码更加优雅和简洁
  • 对于前端和后端维护更方便容易

实现(直接上代码)

1.状态码

这里我就初步定了两种异常状态码,更多状态码可以根据自己的情况去定义

@Getter
public enum ResponseEnum {
SUCCESS(0, "OK"),
PARAMETER_ERROR(1,"参数异常"),
SYSTEM_ERROR(500, "服务器异常,请联系管理员"); ResponseEnum(Integer code, String message) {
this.code = code;
this.message = message;
} private final Integer code;
private final String message;
}

2.统一返回类

注意:这里data最好使用泛型,如果使用的object,那么swagger接口文档将无法显示对应的字段属性定义

public class ResponseModel<T> {
private Integer code;
private String message;
private T data; public ResponseModel(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
} public static ResponseModel<Void> ok() {
return ok(null);
} public static <T> ResponseModel<T> ok(T data) {
return new ResponseModel<>(ResponseEnum.SYSTEM_ERROR.getCode(), ResponseEnum.SYSTEM_ERROR.getMessage(), data);
} public static <T> ResponseModel<T> ok(T data, String message) {
return new ResponseModel<>(ResponseEnum.SYSTEM_ERROR.getCode(), message, data);
} public static ResponseModel<Void> error(Integer statusCode, String message) {
return new ResponseModel<>(statusCode, message, null);
} public static ResponseModel<Void> error(String message) {
return error(ResponseEnum.SYSTEM_ERROR.getCode(), message);
} public static ResponseModel<Void> error() {
return error(ResponseEnum.SYSTEM_ERROR.getCode(), ResponseEnum.SYSTEM_ERROR.getMessage());
}
}

3.自定义异常

这里没啥好说的,自定义个异常继承RuntimeException,加上状态码属性

@Getter
public class BusinessException extends RuntimeException {
private Integer code; public BusinessException(Integer code, String message) {
super(message);
this.code = code;
} public BusinessException(String message) {
super(message);
}
}

4.统一异常处理器

@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalException { @ExceptionHandler(value = BusinessException.class)
public ResponseModel<Void> BusinessExceptionError(BusinessException e) {
log.error("业务异常", e);
if (e.getCode() != null) {
return ResponseModel.error(e.getCode(), e.getMessage());
}
return ResponseModel.error(e.getMessage());
} @ExceptionHandler(value = Exception.class)
public ResponseModel<Void> ExceptionError(Exception e) {
log.error("系统异常", e);
return ResponseModel.error();
}
}

5.使用

如果不用通过返回的话,这里还需要进行异常捕获,而采用统一异常直接return即可,自定义异常直接抛出,有统一异常可以进行处理

//controller层
@ResponseBody
@PostMapping("/test")
public ResponseModel<Void> save() throws Exception {
// 业务操作
return ResponseModel.ok();
} //service
public void save(String name) throws Exception {
if(name == null){
throw new BusinessException(ResponseEnum.PARAMETER_ERROR.getCode(),ResponseEnum.PARAMETER_ERROR.getMessage());
}
}

6.仍存在的问题

访问服务不存在的接口404时,是无法进行捕获的,这个问题小伙伴们可以阅读我之后更新的文章会进行处理

感谢各位小伙伴阅读到最后,如有错误,敬请指正。

1.spring系列之优雅的实现接口统一返回的更多相关文章

  1. webapi接口统一返回请求时间

    webapi接口统一返回请求时间: public class BaseController : ControllerBase { protected ReturnResult<T> Res ...

  2. Java封装接口统一返回数据模板

    现在大多数都使用前后端分离开发模式,前端通过Ajax请求访问后台服务器,后台返回JSON数据供前端操作,这里编写一个统一返回数据模板类,方便日后操作 public class R extends Ha ...

  3. Spring系列18:Resource接口及内置实现

    本文内容 Resource接口的定义 Resource接口的内置实现 ResourceLoader接口 ResourceLoaderAware 接口 Resource接口的定义 Java 的标准 ja ...

  4. Spring系列.Resource接口

    接口简介 JDK中提供了java.net.URL这个类来用于获取不同种类的资源(根据不同前缀的url可以获取不同种类的资源).但是URL这个类没有获取classpath和ServletContext下 ...

  5. Spring系列(零) Spring Framework 文档中文翻译

    Spring 框架文档(核心篇1和2) Version 5.1.3.RELEASE 最新的, 更新的笔记, 支持的版本和其他主题,独立的发布版本等, 是在Github Wiki 项目维护的. 总览 历 ...

  6. Spring 系列: Spring 框架简介 -7个部分

    Spring 系列: Spring 框架简介 Spring AOP 和 IOC 容器入门 在这由三部分组成的介绍 Spring 框架的系列文章的第一期中,将开始学习如何用 Spring 技术构建轻量级 ...

  7. Spring 系列: Spring 框架简介(转载)

    Spring 系列: Spring 框架简介 http://www.ibm.com/developerworks/cn/java/wa-spring1/ Spring AOP 和 IOC 容器入门 在 ...

  8. Spring系列

    Spring系列之访问数据库   阅读目录 一.概述 二.JDBC API的最佳实践 三.Spring对ORM的集成 回到顶部 一.概述 Spring的数据访问层是以统一的数据访问异常层体系为核心,结 ...

  9. 通俗化理解Spring3 IoC的原理和主要组件(spring系列知识二总结)

    ♣什么是IoC? ♣通俗化理解IoC原理 ♣IoC好处 ♣工厂模式 ♣IoC的主要组件 ♣IoC的应用实例 ♣附:实例代码 1.什么是IoC(控制反转)? Spring3框架的核心是实现控制反转(Io ...

随机推荐

  1. clickhouse安装数据导入及查询测试

    官网 https://clickhouse.tech/ quick start ubantu wget https://repo.yandex.ru/clickhouse/deb/lts/main/c ...

  2. 【编程思想】【设计模式】【行为模式Behavioral】状态模式State

    Python版 https://github.com/faif/python-patterns/blob/master/behavioral/state.py #!/usr/bin/env pytho ...

  3. Spring Boot对日志的控制

    一.logback日志技术介绍 Spring Boot中使用的日志技术为logback.其与Log4J都出自同一人,性能要优于Log4J,是Log4J的替代者. 在Spring Boot中若要使用lo ...

  4. 前端浅谈-协议相关(http/https)

    当DNS工作完之后得到了一个网址 https//192.168.1.255/index.html 这个并不符合标准的请求路径.接下来就是https的功能了.讲https前先讲讲它的前身http协议 H ...

  5. [BUUCTF]REVERSE——[FlareOn4]IgniteMe

    [FlareOn4]IgniteMe 附件 步骤: 例行检查,32位程序,无壳 32位ida载入 当满足第10行的if条件时,输出G00d j0b!提示我们成功,看一下sub_401050函数 3.s ...

  6. 替DateDif哭诉一把(Excel函数集团)

    Excel中有个工作表函数DateDif,专门用来计算两日期之间的日差.月差.年差,传说十分好用. 具体用法在此就省略了,好奇的童鞋请自行*度~ 可是,在Excel里,他却是个"没户口&qu ...

  7. 工作组规划器(Project)

    <Project2016 企业项目管理实践>张会斌 董方好 编著 好像前面每分配一次任务,都要打开一个对话框,有木有简单粗暴点的法子啊? 必须有啊! 视图里有一种[工作组规划器],想要粗暴 ...

  8. 数组基础(Excel函数集团)

    此处文章均为本妖原创,供下载.学习.探讨! 文章下载源是Office365国内版1Driver,如有链接问题请联系我. 请勿用于商业! 谢谢 下载地址:https://officecommunity- ...

  9. 用 shell 脚本做自动化测试

    前言 项目中有一个功能,需要监控本地文件系统的变更,例如文件的增.删.改名.文件数据变动等等.之前只在 windows 上有实现,采用的是 iocp + ReadDirectoryChanges 方案 ...

  10. LuoguP7426 [THUPC2017] 体育成绩统计 题解

    Update \(\texttt{2021.3.11}\) 修复了一个笔误. Content 太长了,请直接跳转回题面查看. 数据范围:\(n\leqslant 10^4\),\(0\leqslant ...