作者:京东物流 覃玉杰
1. 简介
Graceful Response是一个Spring Boot体系下的优雅响应处理器,提供一站式统一返回值封装、异常处理、异常错误码等功能。
使用Graceful Response进行web接口开发不仅可以节省大量的时间,还可以提高代码质量,使代码逻辑更清晰。
强烈推荐你花3分钟学会它!
Graceful Response的Github地址: https://github.com/feiniaojin/graceful-response ,欢迎star!
Graceful Response的案例工程代码:https://github.com/feiniaojin/graceful-response-example.git
2. Spring Boot Web API接口数据返回的现状
我们进行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之后的代码,实现同样的返回值封装、异常处理、异常错误码功能,但可以看到代码变得非常简洁,可读性非常强。

GracefulResponse是一个为SpringBoot设计的组件,用于统一返回值封装、异常处理和错误码功能,简化了Controller中的冗余代码,提高了代码可读性。通过引入和配置,开发者可以直接返回业务数据,GracefulResponse会自动处理响应格式和异常转换,降低了接口开发的复杂度。
最低0.47元/天 解锁文章
2258

被折叠的 条评论
为什么被折叠?



