An ebook/comic library service and web client
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 Atheneum."""
  2. from typing import Dict
  3. from werkzeug.exceptions import HTTPException
  4. from atheneum.api.decorators import return_json
  5. from atheneum.api.model import APIResponse, APIMessage
  6. class BaseError(Exception):
  7. """Atheneum 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. """Atheneum 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. """Atheneum Validation Error."""
  34. pass
  35. @return_json
  36. def handle_atheneum_404_error(exception: HTTPException) -> APIResponse:
  37. """Error handler for 404 Atheneum errors."""
  38. return APIResponse(
  39. payload=APIMessage(False, 'Not Found'), status=exception.code)
  40. @return_json
  41. def handle_atheneum_base_error(error: BaseError) -> APIResponse:
  42. """Error handler for basic Atheneum raised errors."""
  43. return APIResponse(payload=error, status=error.status_code)