方法 2 - HackSoft 推荐的方式(续)
if response is None:
if isinstance(exc, ApplicationError):
data = {
"message": exc.message,
"extra": exc.extra
}
return Response(data, status=400)
- 在 DRF 无法处理时(response is None)
- 检查是否是我们的
ApplicationError - 直接返回我们定义的格式
关键逻辑 2:ValidationError 特殊处理
if isinstance(exc, exceptions.ValidationError):
response.data["message"] = "Validation error"
response.data["extra"] = {
"fields": response.data["detail"]
}
- 将验证错误放在
extra.fields中 - 前端可以轻松找到字段级错误
关键逻辑 3:其他错误
else:
response.data["message"] = response.data["detail"]
response.data["extra"] = {}
- 简单地将
detail作为message extra为空对象