【问题标题】:Add custom fields to Django rest_framework APIException将自定义字段添加到 Django rest_framework APIException
【发布时间】:2020-04-01 14:54:46
【问题描述】:

我正在继承 Django 的其余框架 APIException 类来创建自定义 API 异常。例如,我的一个例外如下所示:

class Unauthorized(APIException):
    status_code = 401
    default_detail = 'You have to login first.'
    default_code = 'ERR_UNAUTHORIZED'

我已经编写了一个自定义异常处理程序来修改键名。 这是我的异常处理程序中处理这些异常的部分:

def custom_exception_handler(exc, context):
     response.data['code'] = response.data['detail'].code
     response.data['message'] = response.data['detail']
     print(response.data)
     del response.data['detail']
     return response

因此,我的异常的输出如下所示:

{
    "code": "ERR_UNAUTHORIZED",
    "message": "You have to login first."
}

我需要做的是我想在我的异常中添加一个新字段,以便我的异常输出如下例所示:

{
    "code": "ERR_UNAUTHORIZED",
    "message": "You have to login first.",
    "extra" : "{ "description" : "extra info" }"
}

在我看来,我想像这样抛出这个异常:

raise Unauthorized(extra={ "description" : "extra info" })

我对 Django rest_framework 很陌生,我已经搜索过这个,还尝试将 "another field" 添加到我的自定义异常类字段中,但这无法解决我的问题。有没有办法做这样的事情?

【问题讨论】:

    标签: python django exception django-rest-framework


    【解决方案1】:

    我自己找到了一个答案(这不是很干净)。我们可以在我们的序列化器中抛出异常,如下所示:

     raise serializers.ValidationError({"info" : "test info"})
    

    在自定义异常处理程序中,我们可以像这样处理这种情况:

    def custom_exception_handler(exc, context):
    
        response = exception_handler(exc, context)
    
        if isinstance(exc, ValidationError): 
            resp_copy = response.data
            del response.data
            response.data = {}
            if(response.status_code == 400):
                response.data['code'] = 'ERR_UNAUTHORIZED'
                response.data['message'] = 'some errors occurred'
                response.data['extra'] = {}
                for key in resp_copy:
                    response.data['extra'][key] = resp_copy[key]
    

    输出格式如下:

    {
        "code": "ERR_UNAUTHORIZED",
        "message": "some errors occurred",
        "extra": {
            "info": [
                "test info"
            ]
        }
    }
    

    【讨论】:

      【解决方案2】:

      这样试试

      def custom_exception_handler(exc, context):
           response.data['code'] = response.data['detail'].code
           response.data['message'] = response.data['detail']
      
           response.data['another_field'] = { "description" : "extra info" }
      
           print(response.data)
           del response.data['detail']
           return response
      

      希望对你有所帮助....

      补充答案

      class Unauthorized(Exception):
          def __init__(self, message, errors):
      
              # Call the base class constructor with the parameters it needs
              super(ValidationError, self).__init__(message)
      
              # Now for your custom code...
              self.errors = errors
      

      在你想要的地方引发异常

      raise Unauthorized("Your message")
      

      并捕获异常

      try:
          ...
      except Unauthorized as e:
          print(str(e))
      

      【讨论】:

      • 感谢您的回答。但是,如果我在引发异常时需要发送另一个字段作为参数怎么办? raise Unauthorized(another_field = data)
      猜你喜欢
      • 2011-02-25
      • 1970-01-01
      • 2014-04-02
      • 2013-10-19
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      相关资源
      最近更新 更多