springboot接口返回封装与异常控制
首先,返回有两个状态,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接口返回封装与异常控制的更多相关文章
- springboot 接口返回数据时 net.sf.json.JSONNull["empty"]) 异常
@ResetController返回数据时出现异常 Could not write JSON: Object is null; nested exception is com.fasterxml.ja ...
- 第3章 springboot接口返回json 3-1 SpringBoot构造并返回一个json对象
数据的使用主要还是以JSON为主,我们不会去使用XML. 这个时候我们先不使用@RestController,我们使用之前SpringMVC的那种方式,就是@Controller. @Respons ...
- SpringBoot接口返回去掉空字段
返回的接口中存在值为null或者空的字段过滤掉 @Configuration public class JacksonConfig { @Bean @Primary @ConditionalOnMis ...
- 第3章 springboot接口返回json 3-2 Jackson的基本演绎法
@JsonIgnore private String password; @JsonFormat(pattern="yyyy-MM-dd hh:mm:ss a",locale=&q ...
- SpringBoot接口 - 如何优雅的对接口返回内容统一封装?
在以SpringBoot开发Restful接口时,统一返回方便前端进行开发和封装,以及出现时给出响应编码和信息.@pdai SpringBoot接口 - 如何优雅的对接口返回内容统一封装? RESTf ...
- spring boot 接口返回值封装
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- SpringBoot统一处理返回结果和异常情况
如果文章有帮助到你,还请点个赞或留下评论 原因 在springboot项目里我们希望接口返回的数据包含至少三个属性: code:请求接口的返回码,成功或者异常等返回编码,例如定义请求成功. messa ...
- 【SpringBoot】 一种解决接口返回慢的方式
前言 使用springboot开发后台代码的时候,很核心的一个功能是为前端提供接口,那么很可能你会遇到如下问题: 1. 接口里面调用的service层是第三方库或者第三方后台程序,导致访问很慢. 2. ...
- 项目部署到liunx环境下访问接口返回异常
1.访问接口返回异常 已经连续踩了两次这个坑了.所以记下来了.方便下次搜索! 项目在window下运行正常,无任何异常! 但是部署到liunx环境下的服务器上就有问题 访问静态页面毫无问题,一旦涉及到 ...
随机推荐
- NodeJs之文件上传
NodeJs之文件上传 一,介绍与需求 1.1,介绍 1,multer模块 multer用于处理文件上传的nodejs中间件,主要跟express框架搭配使用,只支持表单MIME编码为multipar ...
- nginx配置https双向验证(ca机构证书+自签证书)
nginx配置https双向验证 服务端验证(ca机构证书) 客户端验证(服务器自签证书) 本文用的阿里云签发的免费证书实验,下载nginx安装ssl,文件夹有两个文件 这两个文件用于做服务器http ...
- BigDecimal(大浮点数)
因为这个单词,和他的四则运算方法总是记不住,所以写入博客,在没有印象的时候再看看自己的博客. BigDecimal的加减乘除不和double float 一样,他需要使用方法来进行加减乘除. 加法:a ...
- ShoppingCart
数据库设计 表结构 [dbo].[AdminInfo] AdminID, AdminName, AdminPassword, RoleID [dbo].[BK_Car] ID, CarID, ISBN ...
- 【简】题解 AWSL090429 【噪音】
因为每次加上一头奶牛 是什么不重要 牛棚之间贡献除清空操作外无影响 就只要考虑 每个牛棚清空分x次 的贡献 x之和为k 求贡献和最小 一个牛棚清空x次 显然平均清空贡献最小 再用等差数列的 ...
- Mysql高性能笔记(一):Schema与数据类型优化
1.数据类型 1.1.几个参考优化原则 a. 更小的通常更好 i.更小的数据类型,占用更少磁盘.内存和CPU缓存,需要的CPU周期更少 ii.如果无法确定哪个数据类型是最好的,就选择不会超过范围的最 ...
- Java 8 特性 —— 函数式接口
函数式接口 概述:接口中只有一个抽象方法. 函数式接口,即适用于函数式编程场景的接口.而 Java 中的函数式编程体现就是 Lambda,所以函数式接口就是可以适用于 Lambda 使用的接口.只有确 ...
- Beyas定理
\(Beyas\)定理 首先由条件概率的计算式有 \[Pr\{A|B\}=\frac{Pr\{A\cap B\}}{Pr\{B\}}\] 结合交换律得到 \[Pr\{A\cap B\}=Pr\{B\} ...
- SDOI 2019 R1 摸鱼记
Day -1 学文化课第一天,也是这周最后一天. 昨晚 mxl 让我们今天下午放学走,大概六点的样子,感觉良好. 早读班主任送来请假条,跟我讲中午放学走??? 很懵逼,以为班主任口胡了,问了一句&qu ...
- 【实用Windows双系统一键备份还原工具】Winclone Pro for Mac
[简介] 今天和大家分享最新的 Winclone Pro 7.3.3 Mac 版本,这是一款Mac上强大易用的Windows分区备份还原工具,类似于Windows上的一键Ghost,能够将 PC 上的 ...