当前位置: 首页 > news >正文

Spring统一处理请求响应与异常

在web开发中,规范所有请求响应类型,不管是对前端数据处理,还是后端统一数据解析都是非常重要的。今天我们简单的方式实现如何实现这一效果

实现方式

  1. 定义响应类型

public class ResponseResult<T> {private static final String SUCCESS_CODE = "000";private static final String FAILURE_CODE = "999";private String code;private String message;private T data;public static <T> ResponseResult<T> ok(T data){ResponseResult responseResult = new ResponseResult();responseResult.setCode(SUCCESS_CODE);responseResult.setData(data);return responseResult;}public static ResponseResult fail(String code, String message){if( code == null ){code = FAILURE_CODE;}ResponseResult responseResult = new ResponseResult();responseResult.setCode(code);responseResult.setMessage(message);return responseResult;}public static ResponseResult fail(String message){return fail(FAILURE_CODE, message);}
}
  1. 定义统一的异常处理流程,通过@RestControllerAdvice@ExceptionHandler注解可以对Controller中的异常统一处理

@RestControllerAdvice
public class ControllerAdviceHandle {@ExceptionHandler(Exception.class)public ResponseResult handleException(Exception exception) {BusException busException;if (exception instanceof BusException asException) {busException = asException;} else {busException = convertException(exception);}return ResponseResult.fail(busException.getCode(), busException.getMessage());}
}
  1. 定义统一响应拦截,通过是实现接口ResponseBodyAdvice,这里可以和上面的异常一起处理

public class ControllerAdviceHandle implements ResponseBodyAdvice {@Overridepublic boolean supports(MethodParameter returnType, Class converterType) {return true;}@Overridepublic Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType,ServerHttpRequest request, ServerHttpResponse response) {if( body instanceof ResponseResult){return body;}return ResponseResult.ok(body);}
}
  1. 定义spring配置,实现自动装配

在resource目录添加自动注入配置META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports,这样通过引入jar就可以自动使用该配置

cn.cycad.web.response.ResponseConfig

应用示例

  1. 比如现在有一个User实体,我们通过继承基类

@RestController
@RequestMapping("/test")
public class TestController {@GetMapping("/{val}")public Object get(@PathVariable("val") String val) throws BusException {if( "1".equals(val) ){throw new BusException("参数错误");}return Map.of("val",val);}}
  1. 通过调用请求,可以看到不管是否异常,结果都是下面的格式

{"code": "999","message": null,"data": null
}
http://www.lryc.cn/news/418685.html

相关文章:

  • SqlServer公用表表达式 (CTE) WITH common_table_expression
  • 常见中间件漏洞
  • elasticsearch的学习(二):Java api操作elasticsearch
  • docker 部署 ElasticSearch;Kibana
  • k8s使用kustomize来部署应用
  • 基于开源FFmpeg和SDL2.0的音视频解码播放和存储系统的实现
  • 保姆级教程,一文了解LVS
  • 【STM32】DMA数据转运(存储器到存储器)
  • 【Android】通过代码打开输入法
  • 爬虫集群部署:Scrapyd 框架深度解析
  • pytorch GPU操作事例
  • linux常见性能监控工具
  • C++ | Leetcode C++题解之第331题验证二叉树的前序序列化
  • 【多模态处理】利用GPT逐一读取本地图片并生成描述并保存,支持崩溃后从最新进度恢复
  • 【rk3588】获取相机画面
  • 数据结构的基本概念
  • AI人工智能机器学习
  • 试用AWS全新神器:Amazon Bedrock的「Open Artifacts」版Claude.ai Artifacts
  • W3C XML 活动
  • vue请求springboot接口下载zip文件
  • PySide6||QPushButton的QSS样式
  • HarmonyOS鸿蒙应用开发之ArkTS基本语法
  • Web开发-CSS篇-上
  • 在mac上通过 MySQL 安装包安装 MySQL 之后,终端执行 mysql 命令报错 command not found: mysql
  • Unity入门4——常用接口
  • 职业教育云计算实验实训室建设应用案例
  • MySQL-MHA高可用配置及故障切换
  • Sentinel 滑动时间窗口源码分析
  • 猎码安卓APP开发IDE,amix STUDIO中文java,HTML5开发工具
  • 【Deep-ML系列】Linear Regression Using Gradient Descent(手写梯度下降)