首先,返回有两个状态,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. Ubuntu安装Navicat 12 for MySQL

    环境准备 要想运行Navicat,必须先安装Wine,这个可以使用下面的命令来安装Wine: ubuntu@ubuntu ~ $ sudo apt-get install wine-stable 安装 ...

  2. Windows下安装配置MongoDB

    Windows下安装配置MongoDB 一,介绍 MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统.在高负载的情况下,添加更多的节点,可以保证服务器性能. MongoDB ...

  3. Spark报错

    1. Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at com.mysql.jdb ...

  4. BaseEntity

    @MappedSuperclasspublic class BaseEntity { @Id @GenericGenerator(name="idGenerator", strat ...

  5. 有这iconfont.woff文件 为什么还报404

    解决方法1.打开服务器IIS管理器,找到MIME类型. 2.添加MIME类型 添加三条: 文件扩展名 MIME类型 .svg image/svg+xml.woff application/x-font ...

  6. 内存泄漏(Memory Leak)

    什么情况下会导致内存泄露(Memory Leak)? Android 的虚拟机是基于寄存器的Dalvik,它的最大堆大小一般是16M,有的机器为24M.因此我们所能利用 的内存空间是有限的.如果我们的 ...

  7. MySql自动备份shell

    MySql黑屏备份是每个运维工程师必备的技能,以下是MySQL自动备份脚本: #/bin/bash#This is mysql backup shell on 2019/4/28 BAKUP_DIR= ...

  8. SNOI 2019 字符串

    SNOI 2019 字符串 题目 题解: 解法一: 记一个数组\(f\),\(f[i]=\min_j\ s[j]\neq s[j+1] (j\geq i)\),直接sort即可,复杂度\(O(nlog ...

  9. Day057--django

    1. http协议 请求的格式(request ---浏览器向服务器发送的消息) 请求方式: URL HTTP/1.1\r\n K1:V1\r\n K2:V2\r\n \r\n 请求正文/请求体(ge ...

  10. sk-learn 决策树的超参数

    一.参数criterion:特征选择标准,[entropy, gini].默认gini,即CART算法. splitter:特征划分标准,[best, random].best在特征的所有划分点中找出 ...