A multipurpose python flask API server and administration SPA
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.7 KiB

  1. """Error definitions for Corvus."""
  2. from typing import Dict
  3. from werkzeug.exceptions import HTTPException
  4. from corvus.api.decorators import return_json
  5. from corvus.api.model import APIResponse, APIMessage
  6. class BaseError(Exception):
  7. """Corvus Base Error Class (5xx errors)."""
  8. def __init__(
  9. self,
  10. message: str = 'Unknown error',
  11. status_code: int = 500,
  12. extra_fields: Dict[str, str] = None) -> None:
  13. """Populate The Error Definition."""
  14. super().__init__(message)
  15. self.message = message
  16. self.status_code = status_code
  17. self.extra_fields = extra_fields
  18. def to_dict(self) -> dict:
  19. """Serialize an error message to return."""
  20. return {
  21. 'message': self.message,
  22. 'status_code': self.status_code
  23. }
  24. class ClientError(BaseError):
  25. """Corvus errors where the client is wrong (4xx errors)."""
  26. def __init__(self,
  27. message: str = 'Unknown client error',
  28. status_code: int = 400,
  29. extra_fields: Dict[str, str] = None) -> None:
  30. """Init for client originated errors."""
  31. super().__init__(message, status_code, extra_fields)
  32. class ValidationError(ClientError):
  33. """Corvus Validation Error."""
  34. pass
  35. @return_json
  36. def handle_corvus_404_error(exception: HTTPException) -> APIResponse:
  37. """Error handler for 404 Corvus errors."""
  38. return APIResponse(
  39. payload=APIMessage(False, 'Not Found'), status=exception.code)
  40. @return_json
  41. def handle_corvus_base_error(error: BaseError) -> APIResponse:
  42. """Error handler for basic Corvus raised errors."""
  43. return APIResponse(payload=error, status=error.status_code)