首先,返回有两个状态,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)
@ResponseBody
public 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)
@ResponseBody
public 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); } }

springboot接口返回封装与异常控制的更多相关文章

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

    @ResetController返回数据时出现异常 Could not write JSON: Object is null; nested exception is com.fasterxml.ja ...

  2. 第3章 springboot接口返回json 3-1 SpringBoot构造并返回一个json对象

    数据的使用主要还是以JSON为主,我们不会去使用XML. 这个时候我们先不使用@RestController,我们使用之前SpringMVC的那种方式,就是@Controller.  @Respons ...

  3. SpringBoot接口返回去掉空字段

    返回的接口中存在值为null或者空的字段过滤掉 @Configuration public class JacksonConfig { @Bean @Primary @ConditionalOnMis ...

  4. 第3章 springboot接口返回json 3-2 Jackson的基本演绎法

    @JsonIgnore private String password; @JsonFormat(pattern="yyyy-MM-dd hh:mm:ss a",locale=&q ...

  5. SpringBoot接口 - 如何优雅的对接口返回内容统一封装?

    在以SpringBoot开发Restful接口时,统一返回方便前端进行开发和封装,以及出现时给出响应编码和信息.@pdai SpringBoot接口 - 如何优雅的对接口返回内容统一封装? RESTf ...

  6. spring boot 接口返回值封装

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  7. SpringBoot统一处理返回结果和异常情况

    如果文章有帮助到你,还请点个赞或留下评论 原因 在springboot项目里我们希望接口返回的数据包含至少三个属性: code:请求接口的返回码,成功或者异常等返回编码,例如定义请求成功. messa ...

  8. 【SpringBoot】 一种解决接口返回慢的方式

    前言 使用springboot开发后台代码的时候,很核心的一个功能是为前端提供接口,那么很可能你会遇到如下问题: 1. 接口里面调用的service层是第三方库或者第三方后台程序,导致访问很慢. 2. ...

  9. 项目部署到liunx环境下访问接口返回异常

    1.访问接口返回异常 已经连续踩了两次这个坑了.所以记下来了.方便下次搜索! 项目在window下运行正常,无任何异常! 但是部署到liunx环境下的服务器上就有问题 访问静态页面毫无问题,一旦涉及到 ...

随机推荐

  1. C# NetStream

    标题:NetStream 关注点:Read.Write 正文: int size = Read(buf, 0, buf.length); 这里一次会读入length个字节,如果小于这个数量,后面的就是 ...

  2. 利用layui前端框架实现对不同文件夹的多文件上传

    利用layui前端框架实现对不同文件夹的多文件上传 问题场景: 普通的input标签实现多文件上传时,只能对同一个文件夹下的多个文件进行上传,如果要同时上传两个或多个文件夹下的文件,是无法实现的.这篇 ...

  3. apache+php项目部署

    先安装apache和php然后进行如下操作(以63服务器的安装路径为例) 1.查看php项目运行的报错信息 路径:  cd  /var/log/httpd/error_log 如果错误如下: 可以尝试 ...

  4. 起步wex5 谷歌浏览器兼容性问题,CheckBox不显示

  5. sqlserver登录名权限和用户名权限语句设置

    在sqlserver的安全体系中分为登录名和用户名,登录名是用于登录整个数据库系统用的,用户名是针对各个具体的数据来创建的用户,所以针对权限设置要有这个两个用户进行分别设置,下面写下用语句设置这两个用 ...

  6. WC2019游记

    本来不打算写游记的,但后来想了想这么一次难忘的经历总该留下点痕迹吧...... DAY-1 走之前的最后一天,因为前一天晚上打了CF,所以早上9点才到机房.写了一道圆方树深深地体会到了来自仙人掌的恶意 ...

  7. php 两个数组,若键相同,则值合并

    <?php $arr1 = array('9' => '4.08', '10' => '0.10', '11' => '4.08', '12' => '0.01'); $ ...

  8. Linux环境配置错误记录

    1.  pip install --special_version  pip10. 版本. 使用命令: python -m pip install pip== 其中, -m 参数的意思是将库中的pyt ...

  9. ACM-自学之旅

    分类 知识清单 数据结构 链式前向星 树状数组 线段树 线段树的区间合并 基于ST表格的RMQ 图论 最近公共祖先 树的直径.树的重心与树的点分治 树的最小支配集,最小点覆盖与最大独立集 求无向连通图 ...

  10. Windows系统CMD下常用命令

    命令    功能ASSOC    显示或修改文件扩展名关联.ATTRIB    显示或更改文件属性.BREAK    设置或清除扩展式 CTRL+C 检查.BCDEDIT    设置启动数据库中的属性 ...