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

devtools/2024/9/24 4:45:28/

在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.ppmy.cn/devtools/92468.html

相关文章

书生.浦江大模型实战训练营——(一)InternStudio+Vscode SSH连接远程服务器+Linux基础指令

最近在学习书生.浦江大模型实战训练营&#xff0c;所有课程都免费&#xff0c;以关卡的形式学习&#xff0c;也比较有意思&#xff0c;提供免费的算力实战&#xff0c;真的很不错&#xff08;无广&#xff09;&#xff01;欢迎大家一起学习&#xff0c;打开LLM探索大门&#xf…

Recyclerview网格布局学习备忘

网格分割线&#xff0c;网格布局代码&#xff1a; 两个链接构成完整代码&#xff1a; Android RecyclerView线性布局详解(1)_Android_脚本之家 (jb51.net) Android RecyclerView网格布局&#xff08;支持多种分割线&#xff09;详解(2)_Android_脚本之家 (jb51.net)

HCIA、OSPF笔记

一、OSI参考模型 1、OSI的结构 应用层&#xff1a;把人类语言转化成编码&#xff0c;为各种应用程序提供网络服务。 表示层&#xff1a;定义一些数据的格式&#xff0c;&#xff08;对数据进行加密、解密、编码、解码、压缩、解压缩&#xff0c;每一层都可以实现&#xff0c…

vue+elementui 表格分页限制最大页码数

vue3element-plus &#xff1a; 在组件里直接使用page-count属性&#xff0c;在获取数据的时候测试一下总条数/每页数量向上取整是否大于1000&#xff0c;是默认count为1000&#xff0c;否则使用计算后的值&#xff1b; vue2 elementui el-pagination &#xff1a;total与pag…

魔方远程时时获取短信内容APP 前端Vue 后端Ruoyi框架(含搭建教程)

前端Vue 后端Ruoyi框架 APP原生JAVA 全兼容至Android14(鸿蒙 澎湃等等) 前后端功能&#xff1a; ①后端可查看用户在线状态(归属地IP) ②发送短信(自定义输入收信号码以及短信内容&#xff0c;带发送记录) ③短信内容分类清晰(接收时间、上传时间等等) ④前后端分离以及A…

Linux Shell面试题大全及参考答案(3万字长文)

目录 解释Shell脚本是什么以及它的主要用途 主要用途 Shell脚本中的注释如何编写? 如何在Shell脚本中定义和使用变量? Shell支持哪些数据类型? 什么是Shell的命令替换?请举例说明。 管道(pipe)和重定向(redirection)有什么区别? 如何在Shell脚本中使用条件语句…

深入理解 RDMA 的软硬件交互机制

作者&#xff1a;羽京 一、前言 随着数据中心的飞速发展&#xff0c;高性能网络不断挑战着带宽与时延的极限&#xff0c;网卡带宽从过去的 10 Gb/s 、25 Gb/s 到如今的 100 Gb/s、200 Gb/s 再到下一代的 400Gb/s 网卡&#xff0c;其发展速度已经远大于 CPU 发展的速度。 为了…

【多线程】JUC的常见类,Callable接口,ReentranLock,Semaphore,CountDownLatch

JUC&#xff1a;java.util.concurrent 一、Callable 接⼝ 接口方法Callablecall&#xff0c;带有返回值Runnablerun&#xff0c;void所以创建一个线程&#xff0c;希望它给你返回一个结果&#xff0c;那么使用 Callable 更加方便一些 比如&#xff0c;创建一个线程&#xff…