如何在Django Rest框架中覆盖异常消息 [英] How to override exception messages in django rest framework

查看:71
本文介绍了如何在Django Rest框架中覆盖异常消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用基于Django类的视图和其余框架

I am using django class based view and rest framework

object = self.get_object()

在详细视图中,如果对象不存在,我确实会收到类似的请求

In Detail view if object does not exist and i do get request like

/user/10

然后我得到此响应

{"detail": "not found"}

现在我想自定义该响应

like

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

但这没用

推荐答案

我们可以实现自定义异常处理函数 ,如果对象不存在,则返回自定义响应。

We can implement a custom exception handler function that returns the custom response in case the object does not exist.

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

In case a object does not exist, Http404 exception is raised. So, we will check if the exception raised is Http404 and if that is the case, we will return our custom exception message in the response.

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设置中。

After defining our custom exception handler, we need to add this custom exception handler to our DRF settings.

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

这篇关于如何在Django Rest框架中覆盖异常消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆