Spring Boot 统一返回结果及异常处理
在 Spring Boot 构建电商基础秒杀项目 (三) 通用的返回对象 & 异常处理 基础上优化、调整
一、通用类
1.1 通用的返回对象
public class CommonReturn {
private Integer code;
private String msg;
private Object data;
private CommonReturn(CommonResult commonResult) {
this.code = commonResult.getCode();
this.msg = commonResult.getMsg();
}
public static CommonReturn success(Object obj) {
CommonReturn commonReturn = new CommonReturn(ResultEnum.SUCCESS);
commonReturn.data = obj;
return commonReturn;
}
public static CommonReturn error(CommonResult commonResult) {
CommonReturn commonReturn = new CommonReturn(commonResult);
return commonReturn;
}
public static CommonReturn error(CommonResult commonResult, String msg) {
CommonReturn commonReturn = new CommonReturn(commonResult);
commonReturn.msg = msg;
return commonReturn;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
public Object getData() {
return data;
}
}
1.2 返回接口
public interface CommonResult {
Integer getCode();
String getMsg();
void setMsg(String msg);
}
1.3 返回枚举
public enum ResultEnum implements CommonResult {
SUCCESS(0, "成功。"),
PARAM_ERROR(1001,"参数验证失败。"),
UNKNOWN_ERROR(9999,"未知错误。"),
;
private Integer code;
private String msg;
ResultEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
@Override
public Integer getCode() {
return code;
}
@Override
public String getMsg() {
return msg;
}
@Override
public void setMsg(String msg) {
this.msg = msg;
}
}
1.4 自定义异常
public class BusinessException extends Exception implements CommonResult {
private CommonResult commonResult;
public BusinessException(CommonResult commonResult) {
super();
this.commonResult = commonResult;
}
public BusinessException(CommonResult commonResult, String msg) {
super();
this.commonResult = commonResult;
this.setMsg(msg);
}
@Override
public Integer getCode() {
return this.commonResult.getCode();
}
@Override
public String getMsg() {
return this.commonResult.getMsg();
}
@Override
public void setMsg(String msg) {
this.commonResult.setMsg(msg);
}
}
二、统一异常处理
@RestControllerAdvice
public class BusinessExceptionHandler {
/**
* 参数校验异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object handleBindException(MethodArgumentNotValidException ex) {
StringBuilder errMsgBuilder = new StringBuilder();
ex.getBindingResult().getFieldErrors().forEach((fieldError) -> {
errMsgBuilder.append(fieldError.getDefaultMessage());
});
return CommonReturn.error(ResultEnum.PARAM_ERROR, errMsgBuilder.toString());
}
/**
* 自定义异常
*/
@ExceptionHandler(BusinessException.class)
public Object handleBusinessException(BusinessException ex){
return CommonReturn.error(ex);
}
@ExceptionHandler(Exception.class)
public Object handleException(Exception ex){
return CommonReturn.error(ResultEnum.UNKNOWN_ERROR, ex.getMessage());
}
}
三、统一返回结果
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response) {
// swagger 不处理
String uri = request.getURI().toString();
if(uri.contains("/v2/api-docs") || uri.contains("/swagger-resources") || uri.contains("/swagger-ui.html")) {
return body;
}
if(body == null) {
return CommonReturn.success(null);
} else if(body instanceof CommonReturn) {
return body;
}
return CommonReturn.success(body);
}
}
测试 Controller
@RestController
public class TestController {
@RequestMapping("/empty")
public void empty() {
}
@RequestMapping("/exception")
public void exception() throws BusinessException {
throw new BusinessException(ResultEnum.PARAM_ERROR);
}
@RequestMapping("/object")
public TestResult object() {
TestResult testResult = new TestResult();
testResult.setId(1L);
testResult.setName("name");
return testResult;
}
class TestResult {
@JsonSerialize(using= ToStringSerializer.class)
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
测试结果
// empty
{
"code": 0,
"msg": "成功。",
"data": null
}
// exception
{
"code": 1001,
"msg": "参数验证失败。",
"data": null
}
// object
{
"code": 0,
"msg": "成功。",
"data": {
"id": "1",
"name": "name"
}
}
同时可以使用 RequestBodyAdvice 统一处理入参,但是不支持 GET 方法
Spring Boot 统一返回结果及异常处理的更多相关文章
- Spring Boot 2 Webflux的全局异常处理
https://www.jianshu.com/p/6f631f3e00b9 本文首先将会回顾Spring 5之前的SpringMVC异常处理机制,然后主要讲解Spring Boot 2 Webflu ...
- spring boot 接口返回值封装
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- spring boot 统一异常处理
需求源自于任何一个业务的编写总会有各种各样的条件判断,需要时时手动抛出异常,又希望让接口返回友好的错误信息. spring boot提供的帮助是自动将异常重定向到路由为/error的控制器 但是我们又 ...
- Spring Boot统一异常处理实践
摘要: SpringBoot异常处理. 原文:Spring MVC/Boot 统一异常处理最佳实践 作者:赵俊 前言 在 Web 开发中, 我们经常会需要处理各种异常, 这是一件棘手的事情, 对于很多 ...
- spring boot 统一接口异常返回值
创建业务 Exception 一般在实际项目中,推荐创建自己的 Exception 类型,这样在后期会更容易处理,也比较方便统一,否则,可能每个人都抛出自己喜欢的异常类型,而造成代码混乱 Servic ...
- Spring Boot 系列教程6-全局异常处理
@ControllerAdvice源码 package org.springframework.web.bind.annotation; import java.lang.annotation.Ann ...
- spring boot 接口返回值去掉为null的字段
现在项目都是前后端分离的,返回的数据都是使用json,但有些接口的返回值存在 null或者"",这种字段不仅影响理解,还浪费带宽,需要统一做一下处理,不返回空字段,或者把NULL转 ...
- Spring Boot 统一异常这样处理和剖析,安否?
话说异常 「欲渡黄河冰塞川,将登太行雪满天」,无论生活还是计算机世界难免发生异常,上一篇文章RESTful API 返回统一JSON数据格式 说明了统一返回的处理,这是请求一切正常的情形:这篇文章将说 ...
- Spring boot之返回json数据
1.步骤: 1. 编写实体类Demo 2. 编写getDemo()方法 3. 测试 2.项目构建 编写实体类Demo package com.kfit; /** * 这是一个测试实体类. */ pub ...
随机推荐
- Python 1-5】Python教程之——字符串
字符串或串(String)是由数字.字母.下划线组成的一串字符. 字符串 字符串就是一系列字符.在Python中,用引号括起的都是字符串,其中的引号可以是单引号, 也可以是双引号,如下所示: &quo ...
- unicode与编码的关系
参考链接先贴上来:https://blog.csdn.net/humadivinity/article/details/79403625https://www.cnblogs.com/kevin2ch ...
- CF1108E2 Array and Segments (Hard version)
线段树 对于$Easy$ $version$可以枚举极大值和极小值的位置,然后判断即可 但对于$Hard$ $version$明显暴力同时枚举极大值和极小值会超时 那么,考虑只枚举极小值 对于数轴上每 ...
- 【Kubernetes学习笔记】-使用Minikube快速部署K8S单机学习环境
介绍 https://minikube.sigs.k8s.io/docs/ Minikube 用于快速在本地搭建 Kubernetes 单节点集群环境,它对硬件资源没有太高的要求,方便开发人员学习试用 ...
- 剑指29:最小的k个数
题目描述 输入n个整数,找出其中最小的K个数.例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4. class Solution {public: vector& ...
- 内网渗透 day12-免杀框架2
免杀框架2 目录 1. IPC管道连接 2. 查看wifi密码 3. Phantom-Evasion免杀框架的运用 4. 自解压(sfx) 5. 数字签名 6. 资源替换 1. IPC管道连接 命名管 ...
- C语言I博课作业04
这个作业属于哪个课程 C语言程序设计II 这个作业要求在哪里 https://edu.cnblogs.com/campus/zswxy/SE2020-1/homework/11489 我在这个作业课程 ...
- Python之Matplot——01.堆叠柱状图的绘制
1.Matplotlib是python的一个绘图库,可以方便的绘制各种图标,是数据可视化的利器. 2.本文我就给大家介绍一下条形图或者说柱状图的绘制 3.代码如下: <1>首先导入模块 1 ...
- Docker + Jenkins + Gitlab + Pytest + Allure 接口自动化测试之持续集成实战终极教程
实战教程篇 前言 这边就不教大家怎么用 pytest 写项目了哦,下面有系列文章能帮助你快速入门 Pytest + Allure 这一篇教程主要是教如何从 0 到 1 搭建自动化测试的持续集成环境 后 ...
- POSIX信号量与互斥锁实现生产者消费者模型
posix信号量 Link with -lpthread. sem_t *sem_open(const char *name, int oflag);//打开POSIX信号量 sem_t *sem_o ...