首先,返回有两个状态,status和code

status标识response的状态,有2个值:0成功,-1服务错误。

code跟业务有关,可以有各种数值,99999服务未知异常,10000参数异常,100001创建订单失败等等。这两个状态用枚举类表示。

ResponseStatus

/*** @Author: ivan* @Description: 服务状态代码* @Date: 18/11/26* @Modified By;*/
public enum ResponseStatus {OK(0, "成功"),ERROR(-1, "服务错误");private int value;private String message;ResponseStatus(int value, String message){this.value = value;this.message = message;}public int getValue() {return value;}public String getMessage() {return message;}}

ResponseCode

/*** @Author: ivan* @Description: 业务状态代码* @Date: 18/11/26* @Modified By;*/
public enum ResponseCode {FORMAL(0, "业务正常"),INVALID_PARAM(100000, "参数错误"),UNKNOWN_FAILED(999999, "服务器未知错误"),SAVE_FAILED(888888, "保存失败"),UPDATE_FAILED(777777, "保存失败"),DELTE_FAILED(666666, "删除失败"),SEARCH_FLOW_FAILED(555555, "查询任务流的执行详情失败!");private int value;private String message;ResponseCode(int value, String message){this.value = value;this.message = message;}public int getValue() {return value;}public String getMessage() {return message;}}

然后,是Response类,简单工厂模式,提供build方法,创建正常返回和错误返回Response。

Response

/*** @Author: ivan* @Description: 返回值封装* @Date: Created in 17:26 18/11/26* @Modified By:*/
public class Response<T> implements Serializable {private int status;private int code;private String message;private Object data;public Response(ResponseStatus status, ResponseCode code, String message, T data) {this.setStatus(status);this.setCode(code);this.setMessage(message);this.setData(data);}public static <T> Response<T> buildSuccessResponse(T data) {return new Response<T>(ResponseStatus.OK, ResponseCode.FORMAL, null, data);}public static <T> Response<T> buildFailResponse(ResponseStatus responseStatus, ResponseCode responseCode,String message, T data) {return new Response<T>(responseStatus, responseCode, message, data);}public int getStatus() {return status;}public void setStatus(ResponseStatus status) {this.status = status.getValue();}public int getCode() {return code;}public void setCode(ResponseCode code) {this.code = code.getValue();}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public Object getData() {return data;}public void setData(Object data) {this.data = data;}
}

如果不想在controller里try-catch一般的异常,并且在一定的条件下通过throw控制代码逻辑,我们需要建立ControllerAdvice。

我这个advice会捕捉ApiException(自定义),一般用业务Code码里的错误码和信息,这时候我们可以返回提示性异常。然后就是Exception普通异常,一般提示服务器未知错误。

我这里还处理了一个参数校验异常

/*** @Author: ivan* @Description: 全局异常处理advice* @Date: Created in 20:21 18/11/26* @Modified By:*/
@ControllerAdvice
public class GlobalExceptionHandler {private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);/***   处理全局异常handler, ApiException为业务异常, 其他为服务器未知异常*/@ExceptionHandler(Exception.class)@ResponseBodypublic Response<String> handle(Exception e) {Response<String> response;if (e instanceof ApiException) {ApiException error = (ApiException) e;response = Response.buildFailResponse(ResponseStatus.ERROR, error.getResponseCode(),error.getResponseCode().getMessage(), null);} else {response = Response.buildFailResponse(ResponseStatus.ERROR, ResponseCode.UNKNOWN_FAILED,ResponseCode.UNKNOWN_FAILED.getMessage(), null);}logger.error("[Exception] message={}", e);return response;}/***  处理参数校验异常handler*/@ExceptionHandler(ValidationException.class)@ResponseBodypublic Response<String> handle(ValidationException e) {StringBuilder sb = new StringBuilder();if(e instanceof ConstraintViolationException){ConstraintViolationException error = (ConstraintViolationException) e;Set<ConstraintViolation<?>> violations = error.getConstraintViolations();for (ConstraintViolation<?> item : violations) {sb.append(item.getMessage());}}logger.error("[Validation] message={}", sb.toString(), e);return Response.buildFailResponse(ResponseStatus.ERROR, ResponseCode.INVALID_PARAM, sb.toString(), null);}}

转载于:https://www.cnblogs.com/kangoroo/p/10696723.html

springboot接口返回封装与异常控制相关推荐

  1. springboot 接口返回数据时 net.sf.json.JSONNull[“empty“]) 异常

    springboot 接口返回数据时 net.sf.json.JSONNull["empty"]) 异常 参考文章: (1)springboot 接口返回数据时 net.sf.js ...

  2. TP5_接口开发之全局异常控制

    前言: 说到异常控制,也许很多会比较陌生,我身边很少人会去写抛异常的代码.但是异常用好了是非常的方便大家开发.首先我们来回顾下哪里可以看到异常,首先我们用框架开发的时候,我们的代码出错或者别的东西.如 ...

  3. springboot 接口返回图片

    一,前言 使用springboot在接口内直接返回图片,生成url地址,浏览器直接访问 需要数据库与实体类 ,下面详细介绍使用方法 二,使用方法 1,返回示例 获取后端接口返回的数据 复制返回的链接在 ...

  4. springboot接口返回数据类型解析问题

    问题:今天在使用postman调试springboot项目的接口的时候一直报错提示: org.springframework.web.HttpMediaTypeNotAcceptableExcepti ...

  5. springboot控制接口返回的字段_SpringBoot实战:SpringBoot之Rest Full接口自定义返回数据类型(ResponseBodyAdvice)...

    我们在日常开发的过程中,经常会要求统一返回数据格式.如要求统一访问格式为 { "success": 请求是否成功, "message": 请求消息, " ...

  6. springboot怎么返回404_深度分析:SpringBoot异常捕获与封装处理,看完你学会了吗?...

    简介 日常开发过程中,难免有的程序会因为某些原因抛出异常,而这些异常一般都是利用try ,catch的方式处理异常或者throw,throws的方式抛出异常不管.这种方法对于程序员来说处理也比较麻烦, ...

  7. springboot接口入参下划线转驼峰以及返回参数驼峰转下划线实现

    转自:springboot接口入参下划线转驼峰以及返回参数驼峰转下划线实现 - 李东平|一线码农 - 博客园 (cnblogs.com) 1.背景 在实际开发中,通常来说java里面是使用驼峰的命名规 ...

  8. SpringBoot统一返回处理出现cannot be cast to java.lang.String异常

    SpringBoot统一返回处理出现cannot be cast to java.lang.String异常 一 问题出现背景: 二 解决方案 三 异常原因分析 原因: 源码详细分析: 正常返回: 返 ...

  9. 调用后台接口返回报错前端隐藏提示_前端异常监控解决方案研究(转)

    前端监控包括行为监控.异常监控.性能监控等,本文主要讨论异常监控.对于前端而言,和后端处于同一个监控系统中,前端有自己的监控方案,后端也有自己等监控方案,但两者并不分离,因为一个用户在操作应用过程中如 ...

最新文章

  1. 《统计学习方法》资源
  2. 解决手机訪问站点时总体相对屏幕缩小问题?(已解决)
  3. Effective C# 原则34:创建大容量的Web API(译)
  4. 换行 输出txt_编程短文:Bash echo如何原生输出带空格的字符串而不换行
  5. 【ECSHOP插件】ECSHOP会员头像,上传头像评论显示头像
  6. JAVA面试技巧之项目介绍
  7. matlab 阶乘函数代码
  8. Vmstat命令详解
  9. R计算两列数据的相关系数_如何用Matlab计算相关系数和偏相关系数
  10. 华为云迁移工具推荐最佳实践:Hyper-V虚拟化迁移到华为云
  11. TZOJ--5447: Irrational Division (博弈)
  12. e.pageX、e.clientX、e.screenX、e.offsetX的区别以及元素的一些CSS属性
  13. 充电桩检测设备TK4860E交流充电桩检定装置
  14. 左手唱片,右手流媒体,环球、索尼、华纳前行之路在何方?
  15. [杂记]LeTeX模板——ppt
  16. 关于LANDesk我们知道些什么
  17. 子组件向父组件传递数据_如何将元素引用向下传递到角度的组件树中
  18. Linux云计算架构师进阶班-Docker-K8s-Devops-Openstack
  19. 情人节表白代码 静态网页表白
  20. CString与string转换

热门文章

  1. 【Java笔记】四种权限修饰符总结
  2. 【动态规划区间dp】蓝桥2019:最优包含
  3. 剑指|| offer1整数除法
  4. H.264官方软件JM源代码简单分析-解码器ldecod
  5. mysql oltp_oltp数据库mysql
  6. java 父类私有成员_java父类私有成员
  7. 大字段 CLOB/BOLB与String互转
  8. zTree节点增删改
  9. HDOJ水题集合1:最小生成树(Kruskal)
  10. 根据mysql生成数据库设计文档_通过navicat工具导出数据库的word格式的设计文档...