方法 2 - HackSoft 推荐的方式(续)
📝 代码详解
处理流程:
flowchart TD
Start([捕获异常 Exception]) --> Normalize["1. 归一化: Django 异常 -> DRF 异常"]
Normalize --> Delegate["2. 委派: 执行 DRF 原生处理器"]
Delegate --> IsHandled{DRF 能处理吗?}
IsHandled -- 不能 (None) --> IsAppError{是 ApplicationError?}
IsAppError -- 是 --> ManualResponse["手动构建 Response"]
IsAppError -- 否 --> Exit500([退出: 抛出 500 错误])
IsHandled -- 能 --> EnsureDetail["3. 确保 data 中 detail 键存在"]
EnsureDetail --> Transform{4. 异常类型?}
Transform -- ValidationError --> FieldError["message = '验证错误'<br/>extra = fields 内容"]
Transform -- 其他 APIException --> GenericError["message = detail 内容<br/>extra = 空"]
ManualResponse --> FinalReshape["5. 最终形态: 统一为 {message, extra}"]
FieldError --> FinalReshape
GenericError --> FinalReshape
FinalReshape --> Cleanup["6. 清洗: 删除 detail 键"]
Cleanup --> End([返回统一格式 Response])
关键逻辑 1:处理 ApplicationError