3

使用した技術:

http://www.django-rest-framework.org

例外: http://www.django-rest-framework.org/api-guide/exceptions/

カスタム exception.py ファイルに rest_framework デフォルトの例を含めました:

from rest_framework.views import exception_handler

import sys

def custom_exception_handler(exc, context=None):

    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc)

    # Now add the HTTP status code to the response and rename detail to error
    if response is not None:
        response.data['status_code'] = response.status_code
        response.data['request'] = request
        response.data['error'] = response.data.get('detail')
        del response.data['detail']

    return response

これにより、「Http404」などの基本的なエラー情報が送信されますが、IP アドレスなどのリクエスト データは送信されません。

リクエストをレスポンスに追加する最良の方法は? 前もって感謝します。

更新(および解決済み):

そのため、最初は DjangoRestFramework 2.4.x を使用してこれを解決しようとしていましたが、そのバージョンにはカスタム例外ハンドラーの要求またはコンテキスト データ オプションがありません。3.1.3 にアップグレードすると、データを応答に簡単に追加できるようになりました。新しいコードは次のようになります (バージョン 3.1.3 を使用):

def custom_exception_handler(exc, request):

# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, request)

# Send error to rollbar
rollbar.report_exc_info(sys.exc_info(), request)

# Now add the HTTP status code to the response and rename detail to error
if response is not None:
    response.data['status_code'] = response.status_code
    response.data['error'] = response.data.get('detail')
    del response.data['detail']

return response
4

1 に答える 1

4

これはあなたのケースでうまくいくはずです。

from rest_framework.views import exception_handler

import sys

def custom_exception_handler(exc, context=None):

    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc)

    # Now add the HTTP status code to the response and rename detail to error
    if response is not None:
        response.data['status_code'] = response.status_code
        response.data['request'] = context['request']
        response.data['error'] = response.data.get('detail')
        del response.data['detail']

    return response

requestに渡されたコンテキストから にアクセスできますcustom_exception_handlerこれはDRF 3.1.0で追加されました。解決されたこの問題も参照してください。

requestDRF<3.1 を使用している場合、例外ハンドラーのコンテキストにはありません。DRF 3.1.3 ( PyPIの最新バージョン) にアップグレードすると、コンテキスト内で簡単にアクセスできrequestます。

DRF 3.1.1 ソース コードから取得:

def get_exception_handler_context(self):
    """
    Returns a dict that is passed through to EXCEPTION_HANDLER,
    as the `context` argument.
    """
    return {
        'view': self,
        'args': getattr(self, 'args', ()),
        'kwargs': getattr(self, 'kwargs', {}),
        'request': getattr(self, 'request', None)
    }

また、ファイルで例外ハンドラを構成する必要がありsettings.pyます。

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}

指定されていない場合、'EXCEPTION_HANDLER'設定はデフォルトで REST フレームワークによって提供される標準の例外ハンドラーになります。

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

ノート:

例外ハンドラーは、発生した例外によって生成された応答に対してのみ呼び出されます。シリアライザーの検証が失敗したときに汎用ビューによって返される HTTP_400_BAD_REQUEST 応答など、ビューによって直接返される応答には使用されません。

于 2015-06-11T16:17:58.060 に答える