1. Create a new file in the app exception.py folder
2. Writing a custom exception handler method exception.py
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.response import Response
exception_handler DEF (EXC, context):
# drf body or default exception handling
response = drf_exception_handler (exc, context)
# 按照一定格式返回异常信息
detail = f"{context.get('view')}-{context.get('request')}-{exc}"
# 服务端错误
if not response:
return Response({
'detail': detail
})
else:
response.data = {'detail': detail}
return response
3. Make the following configurations in the project settings.py file
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'api.exception.exception_handler',
}