1,在项目的utils目录中,创建 exception.py :
from rest_framework.views import exception_handler from rest_framework.response import Response def custom_exception_handler(exc, context): response = exception_handler(exc, context) if response: detail = response.data.get('detail') non_field_errors = response.data.get('non_field_errors') # 异常响应 if detail: #判断异常类型 return Response({'status': 2, 'msg': detail, 'result': {}}) elif non_field_errors: return Response({'status': 1, 'msg': non_field_errors[0], 'result': {}}) else: # return Response({'response': '接口参数错误', 'result': {}, 'code': '', 'tips': response.data}) return Response({'status': 5, 'msg': '接口参数错误', 'result': {}, 'tips': response.data})
2,在项目的settings.py 文件中,添加至全局:
REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'utils.exception.custom_exception_handler', # 自定义异常处理 # 分页 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 5, # 查询,过滤 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), }
3,结束!