一站式统一返回值封装、异常处理、异常错误代码解决方案--最强Sping Boot接口优雅响应处理器|京东云技术团队 - 2.Spring Boot Web API接口数据返回现状
最编程
2024-06-01 17:42:46
...
我们进行Spring Boo Web API接口开发时,通常大部分的Controller代码是这样的:
public class Controller {
@GetMapping("/query")
@ResponseBody
public Response query(Parameter params) {
Response res = new Response();
try {
//1.校验params参数,非空校验、长度校验
if (illegal(params)) {
res.setCode(1);
res.setMsg("error");
return res;
}
//2.调用Service的一系列操作
Data data = service.query(params);
//3.执行正确时,将操作结果设置到res对象中
res.setData(data);
res.setCode(0);
res.setMsg("ok");
return res;
} catch (BizException1 e) {
//4.异常处理:一堆丑陋的try...catch,如果有错误码的,还需要手工填充错误码
res.setCode(1024);
res.setMsg("error");
return res;
} catch (BizException2 e) {
//4.异常处理:一堆丑陋的try...catch,如果有错误码的,还需要手工填充错误码
res.setCode(2048);
res.setMsg("error");
return res;
} catch (Exception e) {
//4.异常处理:一堆丑陋的try...catch,如果有错误码的,还需要手工填充错误码
res.setCode(1);
res.setMsg("error");
return res;
}
}
}
这段代码存在什么问题呢?真正的业务逻辑被冗余代码淹没,可读性太差。
真正执行业务的代码只有
Data data=service.query(params);
其他代码不管是正常执行还是异常处理,都是为了异常封装、把结果封装为特定的格式,例如以下格式:
{
"code": 0,
"msg": "ok",
"data": {
"id": 1,
"name": "username"
}
}
这样的逻辑每个接口都需要处理一遍,都是繁琐的重复劳动。
现在,只需要引入Graceful Response组件并通过@EnableGracefulResponse启用,就可以直接返回业务结果并自动完成response的格式封装。
以下是使用Graceful Response之后的代码,实现同样的返回值封装、异常处理、异常错误码功能,但可以看到代码变得非常简洁,可读性非常强。
public class Controller {
@GetMapping("/query")
@ResponseBody
public Data query(Parameter params) {
return service.query(params);
}
}
推荐阅读
-
用 unordered_set 封装 unordered_map
-
C++ 中的异常处理机制 - 重新抛出异常
-
PCIe 从头开始 (11) - 数据链路层简介
-
JavaScript Fetch API 接口在 Chromium c++ 代码中的实现(二)
-
电影售票选座系统|影院售票|影院订票选座小程序|基于微信小程序的影院售票系统设计与实现(源代码+数据库+文档)
-
FRP 构建内网渗透:云服务器 + 家庭 Linux/Windows 主机 [2024] - 简介
-
.NET开源跨平台桌面和移动应用程序的统一框架--Eto.NET。
-
Postman】使用的接口测试工具-Postman 发送帖子请求
-
第 2 章:信息技术发展(2.2 新一代信息技术及应用) - IV.区块链
-
根据企业现状定制数字化转型路径和战略架构规划