【发布时间】: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