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 ...
随机推荐
- .net 实现签名验签
本人被要求实现.net的签名验签,还是个.net菜鸡,来分享下采坑过程 依然,签名验签使用的证书格式依然是pem,有关使用openssl将.p12和der转pem的命令请转到php实现签名验签 .ne ...
- 直播平台搭建之音视频开发:认识主流视频编码技术H.264
H.264简介 什么是H.264?H.264是一种高性能的视频编解码技术.目前国际上制定视频编解码技术的组织有两个,一个是"国际电联",它制定的标准有H.261.H.263.H.2 ...
- Linux sar命令参数详解
转载自http://www.chinaz.com/server/2013/0401/297942.shtml sar(System Activity Reporter系统活动情况报告)是目前 Linu ...
- Windows平台Python Pyramid实战从入门到进阶:第一个服务
Pyramid是比较流行的Python Web 框架,比较灵活,功能也很强大.最近项目上用到,便打算学习一下.网上教程比较少,而且很多都是针对linux平台的,我是windows土著所以对那些linu ...
- 仿select下拉框
默认状态下,灰色面板出现.当点击页面按钮以及灰色面板外区域时,面板消失;点击按钮,灰色面板出现;点击灰色面板区域,面板不能消失. 主要考察:事件冒泡与取消事件冒泡. 代码: <!DOCTYPE ...
- 6.java设计模式之适配器模式
基本需求: 将一个220V的电压输出成5V的电压,其中220V电压为被适配者,变压器为适配器,5v电压为适配目标 基本介绍: 适配器模式属于结构型模式,将某个类的接口转换成客户端期望的另一个接口表示, ...
- Innodb之线程独享内存
引用链接: https://blog.csdn.net/miyatang/article/details/54881547 https://blog.csdn.net/wyzxg/article/de ...
- __all__有趣的属性
python有趣的属性__all__可用于模块导入时限制,如:from module import *此时被导入模块若定义了__all__属性,则只有all内指定的属性.方法.类可被导入:若没定义,则 ...
- 动态导航栏和JavaScript箭头函数
动态导航栏和JavaScript箭头函数 今天我们来写一下动态的导航栏,并且学一下JavaScript的箭头函数等相关问题. 样式如下所示: html中执行代码如下所示: <!DOCTYPE h ...
- SpringSecurity之授权
SpringSecurity之授权 目录 SpringSecurity之授权 1. 写在前面的话 2. web授权 1. 建库 2. 添加查询权限的接口 3. 前端页面的编写 4. SpringSec ...