例外処理の例外

次のようにフレームを扱うDRFのデフォルトの例外:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
}

デフォルトのrest_framework.viewsモジュール内exception_handlerの関数の例外処理

カスタム例外処理

カスタム例外ハンドラ、例外ハンドラDRFデフォルトのベースフレーム、いくつかの追加の例外処理、データベース処理などを追加することができます
1)カスタム例外ハンドラを

from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework import status
from django.db import DatabaseError

def exception_handler(exc, context):
    # 先调用DRF框架的默认异常处理函数
    response = drf_exception_handler(exc, context)

    if response is None:
        # 补充数据库的异常处理
        if isinstance(exc, DatabaseError):
            response = Response({'detail': '数据库错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

    return response

2)フレームプロファイルsettings.pyにDRF例外ハンドラを変更します

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'booktest.utils.exceptions.exception_handler'
}

おすすめ

転載: www.cnblogs.com/oklizz/p/11291042.html