Files
lpt-be/.agents/roles/api-response.md
T

31 lines
2.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 响应规范与 DTO 转换
- **功能**:统一 API 的响应形态、错误文案风格与 DTO 转换方式。
- **何时用**:新增或修改接口返回值、处理异常、增删 DTO 字段或自定义映射时。
## 响应规范
- 成功:`CommonResult.success(data)`,code=200。
- 业务错误:`CommonResult.error(msg)`,code=400,HTTP 200。
- 未登录:`GlobalExceptionHandler.handleNotLogin()`,HTTP 401 + code=401。
- 参数校验失败:`MethodArgumentNotValidException`,code=400。
- 用户可见错误文案必须口语化、可理解,避免“无法生成”“不存在”等技术化表述;技术细节写入日志。例如无学习报告时应提示“这个任务还没开始学习哦,学习后产生学习报告后再来吧”,而不是“没有学习报告,无法生成思维导图”。
## 出参和入参的边界
- **实体不出 controller**:`CommonResult<XxxEntity>`、`CommonResult<Page<XxxEntity>>` 都不行,出参一律是 `dto/` 下的类。
实体带租户与审计列,库表形状一改就直接击穿 API 契约,前端还得跟着改。
- **请求体用 DTO,不用 `Map<String, String>`**:`Map` 丢类型、丢校验、丢字段名,只能在 service 里 `get("xxx")` 拼字符串;
每个端点一个 request DTO + `@Valid`。
- **`CommonResult` 不写裸类型**:一律 `CommonResult<T>`,哪怕是错误分支也给出 `data` 的类型;裸类型在生成文档与前端类型推导上都退化成 `any`。
存量:`GlobalExceptionHandler` 的 7 个 handler 仍是裸 `CommonResult`。
- **未知异常映射 500**:`@ExceptionHandler(Exception.class)` 返回 `CommonResult.serverError`(code=500),不能复用参数错误的 400,
否则系统故障被说成「参数不对」。存量:该兜底 handler 现在返回 400。
## DTO 转换
- MapStruct 编译期生成 `*ConvertImpl.java`,同名属性自动映射。
- 默认 `unmappedTargetPolicy = IGNORE`。
- 自定义映射使用 `@Mapping(source, target)`。
- 增删 DTO 字段后必须重新编译,否则生成代码不含新字段。