响应封装使用说明 - oljc/arco-serve GitHub Wiki
本项目统一封装了 API 响应结构,用于标准化所有接口的返回格式。它采用 record 类型实现,包含了完整的响应信息。
-
❌ 前端每个接口都要特判成功/失败格式;
-
❌ 错误信息格式不一致,不利于展示;
-
❌ 后端日志没有 traceId,排查困难;
-
❌ 网关、接口文档工具不好解析;
-
❌ 出现异常时,信息泄漏或格式混乱。
-
✅ 简化开发者工作(前后端);
-
✅ 提高异常处理一致性;
-
✅ 标准化接口便于自动化工具解析;
-
✅ 降低维护成本和出错概率;
-
✅ 自动注入 traceId,便于链路追踪。
使用 ApiResponse 作为 API 返回结果结构,便于前后端联调、异常处理、日志追踪等场景。主要是为了方便在业务开发时不用每次都手动构建、书写冗余代码。
响应结构示例:
// ✅ 成功响应
{
"status": "success",
"code": 200,
"message": "操作成功",
"data": { /* 数据 */ },
"traceId": "abc123",
"timestamp": 1704092400000
}
// ❌ 错误响应
{
"status": "error",
"code": 422,
"message": "参数验证失败",
"error": {
"email": "格式不正确",
"age": "必须为正整数"
},
"traceId": "9ff3ea4c25b14d3f8b26422cabc44d0d",
"timestamp": 1704092400000
}
1.成功返回数据
@GetMapping("/hello")
public ApiResponse<String> hello() {
return ApiResponse.success("Hello World");
}
{
"status": "success",
"code": 200,
"message": "操作成功",
"data": "Hello World",
"traceId": "def456",
"timestamp": 1704092400000
}
2.成功但不返回数据
@PostMapping("/user")
public ApiResponse<Void> createUser(@RequestBody UserDTO user) {
userService.create(user);
return ApiResponse.success();
}
{
"status": "success",
"code": 200,
"message": "操作成功",
"data": null,
"traceId": "def456",
"timestamp": 1704092400000
}
3.自定义提示语
@GetMapping("/hello")
public ApiResponse<String> hello() {
return ApiResponse.success("Hello World", "自定义信息");
}
{
"status": "success",
"code": 200,
"message": "自定义信息",
"data": "Hello World",
"traceId": "def456",
"timestamp": 1704092400000
}
1.手动构造错误返回
@GetMapping("/hello")
public ApiResponse<String> hello() {
return ApiResponse.error(400, "请求参数无效");
}
- 返回带错误详情
@GetMapping("/hello")
public ApiResponse<String> hello() {
return ApiResponse.error(Code.VALIDATION_ERROR, Map.of("email", "格式不正确"));
}
{
"status": "error",
"code": 422,
"message": "参数验证失败",
"error": {
"email": "格式不正确"
},
"traceId": "xxxxxx",
"timestamp": 1704092400000
}
- 抛出业务异常(推荐方式)
@GetMapping("/data")
public List<User> getUsers() {
....
if (userNotFound) {
throw new BusinessException(Code.DATA_NOT_FOUND);
}
}
统一异常处理器将自动转换为标准 ApiResponse 错误格式。
如果启用了自动包装机制(通常使用 ResponseBodyAdvice 实现),以下方式也会自动转换为统一响应:
@GetMapping("/simple")
public String getString() {
return "Hello World"; // 自动包装
}
自动包装:
{
"status": "success",
"code": 200,
"message": "操作成功",
"data": "Hello World",
"traceId": "xxxxx",
"timestamp": 1704092400000
}
@GetMapping("/data")
public List<User> getUsers() {
return userService.findAll(); // 自动包装
}