1.在app文件夹下新建exception.py文件
2.在exception.py书写自定义异常处理方法
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.response import Response
def exception_handler(exc, context):
# 主体还是drf默认的异常处理方法
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.在项目settings.py文件下进行如下配置
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'api.exception.exception_handler',
}