gpt4 book ai didi

python - 如何覆盖 django rest 框架中的异常消息

转载 作者:太空宇宙 更新时间:2023-11-03 15:05:33 27 4
gpt4 key购买 nike

我正在使用基于 Django 类的 View 和休息框架

object = self.get_object()

在详细 View 中如果对象不存在并且我确实收到类似的请求

/user/10

然后我得到这个响应

{"detail": "not found"}

现在我想自定义那个响应

喜欢

try:
obj = self.get_object()
except:
raise Exception("This object does not exist")

但是那是行不通的

最佳答案

我们可以实现一个custom exception handler function 在对象不存在的情况下返回自定义响应。

如果对象不存在,将引发Http404 异常。因此,我们将检查引发的异常是否为 Http404,如果是,我们将在响应中返回自定义异常消息。

from rest_framework.views import exception_handler
from django.http import Http404

def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)

if isinstance(exc, Http404):
custom_response_data = {
'detail': 'This object does not exist.' # custom exception message
}
response.data = custom_response_data # set the custom response data on response object

return response

定义自定义异常处理程序后,我们需要将此自定义异常处理程序添加到我们的 DRF 设置中。

REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}

关于python - 如何覆盖 django rest 框架中的异常消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33125139/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com