如何在django rest框架中使用自定义错误代码抛出自定义异常并覆盖异常响应中的默认字段

时间:2015-09-24 14:50:48

标签: django django-rest-framework

我想知道如何在django rest框架中抛出自定义异常,其中包含自定义error_code和自定义消息。我对 APIException()不感兴趣,因为此函数不允许在运行时设置错误代码。另外,我想知道如何更改异常消息的详细信息关键json响应。

3 个答案:

答案 0 :(得分:1)

  

我找到了所有问题的解决方案

api_exceptions.py

from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException

custom_exception_handler

def custom_exception_handler(exc, context):

    response = exception_handler(exc, context)

    if response is not None:
        response.data['status_code'] = response.status_code

        #replace detail key with message key by delete detail key
        response.data['message'] = response.data['detail']
        del response.data['detail']

    return response

CustomApiException

class CustomApiException(APIException):

    #public fields
    detail = None
    status_code = None

    # create constructor
    def __init__(self, status_code, message):
        #override public fields
        CustomApiException.status_code = status_code
        CustomApiException.detail = message

settings.py

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'utilities.helpers.api_exceptions.custom_exception_handler',
}

your_view.py

raise CustomApiException(333, "My custom message")

#json response
{
  "status_code": 333,
  "message": "My custom message"
}

答案 1 :(得分:0)

你可以使用一个返回dict的简单函数:

...

responsedic = {}
response_error_message(response_dic, message='Custom message', http_status=Custom_http_status)
return Response(response_dic)

您认为的电话:

keytool -keypasswd -alias <alias name> -keystore <keystore path>

答案 2 :(得分:0)

from rest_framework import exceptions

class ServiceUnavailableError(exceptions.APIException):
    status_code = status.HTTP_503_SERVICE_UNAVAILABLE
    default_detail = "Service unavailable."

# your views.py
raise ServiceUnavailableError("Override message.")