[Django] DRFカスタム例外処理

1.デフォルトの例外処理

DRFには独自の例外キャプチャメカニズムがあり、APIException、Http404、PermissionDenied、およびその他の例外をキャプチャできます。
処理関数はrest_framework.views.exception_handlerにあります。以下はそのソースコードです。

def exception_handler(exc, context):
	...
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    if isinstance(exc, exceptions.APIException):
        headers = {
    
    }
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {
    
    'detail': exc.detail}

        set_rollback()
        return Response(data, status=exc.status_code, headers=headers)

    return None

2.カスタム例外処理

DRFのデフォルトの例外処理関数は、プロジェクトの他の例外処理を満たすことができないため、カスタマイズする必要があります。つまり、re-exception_handler()メソッドです。

新しいpyファイルを作成し、exception_handler()メソッドを定義し、DRFのデフォルトのソースコードをコピーして変更し、最初にデフォルトの処理メソッドで処理させます。処理できない場合は、独自の方法を使用します。それでも処理できない場合は、無し

BooksTest / exceptions.py

def exception_handler(exc, context):
    # 处理得了返回一个响应,处理不了返回None
    
    # 1、把异常对象交给DRF的异常处理函数去处理
    response = drf_exception_handler(exc, context)
    if response:
        # response不为None,说明drf自行处理异常
        return response

    # 2、如果DRF异常处理函数无法处理,我们自行处理,例如处理除数为零的异常、数据库错误的异常等
    if isinstance(exc, ZeroDivisionError):
        return Response({
    
    'errmsg': '除数不能为零'})
    if isinstance(exc, DatabaseError):
        return Response({
    
    'errmsg': '数据库错误!'})

    return None

exception_handler()を作成しましたが、Djangoはそれを認識していないため、デフォルトのハンドラーの代わりに使用するように指定する必要があります

settings.py

REST_FRAMEWORK = {
    
    
    # ......
    # 自定义异常处理函数的导包路径
    'EXCEPTION_HANDLER': 'BooksTest.exceptions.exception_handler',
}

おすすめ

転載: blog.csdn.net/qq_39147299/article/details/108772941