在DRF中,如何通过自定义异常处理器注入完整的`ErrorDetail`到响应中?

0 投票
1 回答
27 浏览
提问于 2025-04-12 15:29

我在使用DRF(Django REST Framework)时,创建了一个比较复杂的自定义处理器。比如,对于某个特定的响应,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() 方法,它在出现异常时会返回正是这个格式。但我现在是在响应的层面上。

1 个回答

0

我不知道你是否在用这个,不过你可以使用 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/"
}

另外,它还可以接收从 validate 在序列化器中抛出的错误信息。

这里有相关的文档:custom_exception_handler

撰写回答