exception.py 765 B

12345678910111213141516171819202122232425
  1. """
  2. 自定义异常处理
  3. 通过restformwork 的setting配置引用 REST_FRAMEWORK --> EXCEPTION_HANDLER
  4. """
  5. from rest_framework.views import exception_handler
  6. from rest_framework.views import Response
  7. from rest_framework import status
  8. def custom_exception_handler(exc, context):
  9. response = exception_handler(exc, context)
  10. if response is None:
  11. return Response({
  12. 'code': status.HTTP_500_INTERNAL_SERVER_ERROR,
  13. 'msg': '{exc}'.format(exc=exc),
  14. 'data': ''
  15. }, status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)
  16. else:
  17. return Response({
  18. 'code': response.status_code,
  19. 'msg': '{exc}'.format(exc=exc),
  20. 'data': ''
  21. }, status=200, exception=True)