django rest framework 自定義異常返回

上一節給大家介紹了自定義Response返回信息,但那個只用於正確的返回success,但是當我們用到了權限
auth 401、方法不允許method 405,等等,這時候我們就用自己自定義異常返回信息

1、定義settings配置文件

#定義異常返回的路徑腳本位置

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'common.utils.custom_execption.custom_exception_handler',
}

2、定義腳本

#注意,腳本路徑需要與settings.py 定義的一樣

from rest_framework.views import exception_handler

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)

    # Now add the HTTP status code to the response.
    if response is not None:
        print(response.data)
        response.data.clear()
        response.data['code'] = response.status_code
        response.data['data'] = []

        if response.status_code == 404:
            try:
                response.data['message'] = response.data.pop('detail')
                response.data['message'] = "Not found"
            except KeyError:
                response.data['message'] = "Not found"

        if response.status_code == 400:
            response.data['message'] = 'Input error'

        elif response.status_code == 401:
            response.data['message'] = "Auth failed"

        elif response.status_code >= 500:
            response.data['message'] =  "Internal service errors"

        elif response.status_code == 403:
            response.data['message'] = "Access denied"

        elif response.status_code == 405:
            response.data['message'] = 'Request method error'
    return response

#無需調用,報錯的時候他自己會調用!!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章