首先,返回有两个状态,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. dva

    import React, { PureComponent } from "react"; import { Chart, Geom, Axis, Tooltip, Coord, ...

  2. Fetch API & Async Await

    Fetch API & Async Await const fetchJSON = (url = ``) => { return fetch(url, { method: "G ...

  3. springboot实现简单的文件上传

    承接上一篇,这里记录一下简单的springboot文件上传的方式 首先,springboot简单文件上传不需要添加额外的jar包和配置 这里贴一下后端controller层的实现代码 补一份前台的HT ...

  4. flex布局实例demo全解

    上篇文章介绍了Flex布局的语法,今天介绍常见布局的Flex写法. 你会看到,不管是什么布局,Flex往往都可以几行命令搞定. 我只列出代码,详细的语法解释请查阅<Flex布局教程:语法篇> ...

  5. Python实现常用排序算法

    Python实现常用排序算法 冒泡排序 思路: 它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来.走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完 ...

  6. python并发编程之多线程基础知识点

    1.线程理论知识 概念:指的是一条流水线的工作过程的总称,是一个抽象的概念,是CPU基本执行单位. 进程和线程之间的区别: 1. 进程仅仅是一个资源单位,其中包含程序运行所需的资源,而线程就相当于车间 ...

  7. You Are the One HDU - 4283 (区间DP)

    Problem Description The TV shows such as You Are the One has been very popular. In order to meet the ...

  8. 洛谷 P5110 块速递推

    题目大意: 给定一个数列a满足递推式 \(An=233*an-1+666*an-2,a0=0,a1=1\) 求这个数列第n项模\(10^9+7\)的值,一共有T组询问 \(T<=10^7\) \ ...

  9. ubuntu mirror

    # apt-mirror configuration file ## The default configuration options (uncomment and change to overri ...

  10. Python 防止mysql 注入的两种方式

    Python防止sql注入一般有两种方法 1.escape_string   MySQLdb.escape_string(param) 注意:如果报错出现 'ascii' codec can't en ...