error.py 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*- coding: utf-8 -*-
  2. import marshmallow
  3. from hapic.processor import ProcessValidationError
  4. class ErrorBuilderInterface(marshmallow.Schema):
  5. """
  6. ErrorBuilder is a class who represent a Schema (marshmallow.Schema) and
  7. can generate a response content from exception (build_from_exception)
  8. """
  9. def build_from_exception(self, exception: Exception) -> dict:
  10. """
  11. Build the error response content from given exception
  12. :param exception: Original exception who invoke this method
  13. :return: a dict representing the error response content
  14. """
  15. raise NotImplementedError()
  16. def build_from_validation_error(
  17. self,
  18. error: ProcessValidationError,
  19. ) -> dict:
  20. """
  21. Build the error response content from given process validation error
  22. :param error: Original ProcessValidationError who invoke this method
  23. :return: a dict representing the error response content
  24. """
  25. raise NotImplementedError()
  26. class DefaultErrorBuilder(ErrorBuilderInterface):
  27. message = marshmallow.fields.String(required=True)
  28. details = marshmallow.fields.Dict(required=False, missing={})
  29. code = marshmallow.fields.Raw(missing=None)
  30. def build_from_exception(self, exception: Exception) -> dict:
  31. """
  32. See hapic.error.ErrorBuilderInterface#build_from_exception docstring
  33. """
  34. # TODO: "error_detail" attribute name should be configurable
  35. return {
  36. 'message': str(exception),
  37. 'details': getattr(exception, 'error_detail', {}),
  38. 'code': None,
  39. }
  40. def build_from_validation_error(
  41. self,
  42. error: ProcessValidationError,
  43. ) -> dict:
  44. """
  45. See hapic.error.ErrorBuilderInterface#build_from_validation_error
  46. docstring
  47. """
  48. return {
  49. 'message': error.message,
  50. 'details': error.details,
  51. 'code': None,
  52. }