首先,返回有两个状态,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. [Java]list集合为空或为null的区别

    判断的是list这个集合的问题,当前需要判断list内值的问题. 简述判断一个list集合是否为空,我们的惯性思维是判断list是否等于null即可,但是在Java中,list集合为空还是为null, ...

  2. [ffmpeg] 滤波

    ffmpeg中有很多已经实现好的滤波器,这些滤波器的实现位于libavfilter目录之下,用户需要进行滤波时,就是是调用这些滤波器来实现的.ffmpeg对于调用滤波器有一整套的调用机制. 基本结构 ...

  3. docker容器启动haproxy

    1.在本地新增haproxy.cfg文件(本次haproxy.cfg文件路径为/root/haproxy.cfg),内容如下: #---------------- # Global settings ...

  4. win10 安装docker

    看介绍说docker不支持win10家庭版,但是一搜安装教程也有好多在家庭版上安装的,而且也不麻烦,不知道咋回事 1.查看虚拟化状态 一开始我的是没有开启的,从bios开启的 一般是开始按F2,进入b ...

  5. Codeforces Round #543

    (比赛链接)[http://codeforces.com/contest/1120] A 给出一个长度为m的序列a 可以删除一些数 使得最后从没删的第一个数开始 每k个一截 截出的n个多重集合中 至少 ...

  6. <TCP/IP原理> (四) IP编址

    1.IP地址的基本概念:作用.结构.类型 2.特殊地址:作用.特征 网络地址.广播地址(直接.受限) 0.0.0.0 环回地址 3.单播.多播.广播地址:特征 4.专用地址:作用.范围 5.计算和应用 ...

  7. Django中ORM介绍

    Object Relational Mapping(ORM) ORM介绍 ORM概念 对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据 ...

  8. P4180 严格次小生成树[BJWC2010] Kruskal,倍增

    题目链接\(Click\) \(Here\). 题意就是要求一个图的严格次小生成树.以前被题面吓到了没敢做,写了一下发现并不难. 既然要考虑次小我们就先考虑最小.可以感性理解到一定有一种次小生成树,可 ...

  9. 获取windows凭证管理器明文密码

    1.运行cmdkey /list查看windows保存凭证 方法1.mimikaz mimikatz vault::cred 2.利用powershell尝试获取 windows 普通凭据类型中的明文 ...

  10. MapReduce-CombineTextInputFormat 切片机制

    MapReduce 框架默认的 TextInputFormat 切片机制是对任务按文件规划切片,如果有大量小文件,就会产生大量的 MapTask,处理小文件效率非常低. CombineTextInpu ...