api_exception.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. """
  2. api_exception -
  3. auther: tanlie
  4. date: 2026/8/23
  5. """
  6. from flask import request, json
  7. from werkzeug.exceptions import HTTPException
  8. class APIException(HTTPException):
  9. code = 500
  10. msg = 'sorry, we made a mistake (* ̄︶ ̄)!'
  11. error_code = 999
  12. def __init__(self, msg=None, code=None, error_code=None, headers=None):
  13. if code:
  14. self.code = code
  15. if error_code:
  16. self.error_code = error_code
  17. if msg:
  18. self.msg = msg
  19. super(APIException, self).__init__(msg, None)
  20. def get_body(self, environ=None, scope=None, *args, **kwargs):
  21. body = dict(
  22. msg=self.msg,
  23. error_code=self.error_code,
  24. request=request.method + ' ' + self.get_url_no_param()
  25. )
  26. text = json.dumps(body)
  27. return text
  28. def get_headers(self, environ=None, scope=None, *args, **kwargs):
  29. """Get a list of headers.
  30. Werkzeug/Flask may pass ``environ`` and ``scope`` positional arguments in
  31. newer versions, so accept them for compatibility.
  32. """
  33. return [("Content-Type", "application/json")]
  34. @staticmethod
  35. def get_url_no_param():
  36. full_path = str(request.full_path)
  37. main_path = full_path.split('?')
  38. return main_path[0]