【问题标题】:restframework custom EXCEPTION_HANDLER not effect休息框架自定义异常处理程序不影响
【发布时间】:2022-08-22 21:56:43
【问题描述】:

在一个新项目中自定义异常处理程序正在工作,但对于我的旧项目它不工作,我按照文档custom exception handler

写作。我在我的异常处理程序中设置了打印,但它没有显示任何东西。(异常将被捕获,但使用默认处理程序。)

# myapp.exception.py
from rest_framework.views import exception_handler, Response
from rest_framework.exceptions import APIException


def custom_exception(exc, context):
    response = exception_handler(exc, context)
    print(exc)
    if response is not None:
        response.data[\'exception\'] = \'h\'
    else:
        response = Response(data={\'abc\':123}, status=500)
    return  response
# settings.py

REST_FRAMEWORK = {
    \'EXCEPTION_HANDLER\': \'basuser.exception.custom_exception\'
}
INSTALLED_APPS = [
\'...\',
\'...\',
\'rest_framework\'
]
#views.py
class CustomException(APIException):
    status_code = 401
    default_detail = \'detail exception\'
    default_code = \'custom_exception\'

class TestPage(APIView):


    def get(self, request,format=None):
        return Response({\'data\':100})

    def post(self, request):
        raise CustomException()

# out put
Unauthorized: /testpage/
[03/Feb/2022 03:33:21] \"POST /testpage/ HTTP/1.1\" 401 21

# json response
{
    \"detail\": \"detail exception\"
}

太混乱了...

  • 请分享您的完整 settings.py。我猜您可能会为 REST_FRAMEWORK 变量设置一个新值,这会使您的当前值消失并使用默认处理程序。

标签: python django-rest-framework exceptionhandler


【解决方案1】:

解决了,setting.py.REST_FRAMEWORK['EXCEPTION_HANDLER'] 没有效果。

rest_settings.DEFAULTS['EXCEPTION_HANDLER'] = 'basuser.exception.custom_exception'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-23
    • 2011-07-13
    • 2015-10-18
    • 2023-03-04
    • 2018-01-18
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多