我在 DRF 中使用了一个非常复杂的自定义处理程序。 例如,对于给定的响应,
response.data
可能类似于:
{'global_error': None, 'non_field_errors': [], 'field_errors': {'important_field': [ErrorDetail(string='Ce champ est obligatoire.', code='required')]}}
但是,当从API获取实际响应时,
ErrorDetail
将被转换为简单的字符串,丢失代码信息。
是否有一种简单的方法可以确保
ErrorDetail
始终在响应中写入 {"message": "...", "code": "..."}
,而无需在自定义处理程序中手动转换响应?
我知道存在 DRF
get_full_details()
方法,它在异常时返回此值。但我是响应级别。
我不知道您是否正在使用它,但您可以使用
custom_exception_handler
将引发的任何异常转换为您提供的格式。这是一个例子:
def custom_exception_handler(exc, context):
response = exception_handler(exc, context)
if response is not None:
response.data["timestamp"] = datetime.now().isoformat()
response.data["error_type"] = exc.__class__.__name__
response.data["path"] = context["request"].path
return response
使用它,这就是它产生的结果:
{
"detail": "Authentication credentials were not provided.",
"timestamp": "2024-03-29T20:09:02.228370",
"error_type": "NotAuthenticated",
"path": "/tools/"
}
P.S:它还可以将详细信息作为从序列化器中的
validate
引发的异常。
这里是文档:custom_execption_handler