You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

exceptions.py 6.5 kB

5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # Copyright 2019 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Exception module."""
  16. from importlib import import_module
  17. from mindinsight.utils.constant import MindInsightModules, GeneralErrors
  18. class MindInsightException(Exception):
  19. """
  20. Base class for MindInsight exception.
  21. Examples:
  22. >>> raise MindInsightException(GeneralErrors.PATH_NOT_EXISTS_ERROR, 'path not exists')
  23. >>> raise MindInsightException(DataVisualErrors.CUSTOMIZED_ERROR, 'datavisual error message')
  24. """
  25. RUNTIME = 1
  26. TYPE = 1
  27. LEVEL = 0
  28. SYSID = 42
  29. def __init__(self, error, message, http_code=400):
  30. """
  31. Initialization of MindInsightException.
  32. Args:
  33. error (Enum): Error value for specified case.
  34. message (str): Description for exception.
  35. http_code (int): Http code for exception. Default is 400.
  36. """
  37. if isinstance(message, str):
  38. message = ' '.join(message.split())
  39. super(MindInsightException, self).__init__(message)
  40. self.error = error
  41. self.message = message
  42. self.http_code = http_code
  43. def parse_module(self):
  44. """
  45. Parse module according to error enum class.
  46. Note:
  47. Each enum value, excluding GENERAL, has an Errors class name starting with the enum value
  48. in Camel-Case referring to specific module.
  49. Returns:
  50. Enum, module for specified error.
  51. """
  52. module = None
  53. constant = import_module('mindinsight.utils.constant')
  54. errors_names = [item for item in dir(constant) if item.endswith('Errors')]
  55. for name in errors_names:
  56. errors_cls = getattr(constant, name)
  57. if isinstance(self.error, errors_cls):
  58. key = name[:-len('Errors')].upper()
  59. module = getattr(MindInsightModules, key, None)
  60. break
  61. return module
  62. @property
  63. def error_code(self):
  64. """
  65. Transform exception no to MindInsight error code.
  66. code compose(4bytes):
  67. runtime 2bits, type 2bits, level 3bits, sysid 8bits, modid 5bits, value 12bits.
  68. num = ((0xFF & runtime) << 30) \
  69. | ((0xFF & type) << 28) \
  70. | ((0xFF & level) << 25) \
  71. | ((0xFF & sysid) << 17) \
  72. | ((0xFF & modid) << 12) \
  73. | (0x0FFF & value)
  74. Returns:
  75. str, Hex string representing the composed MindInsight error code.
  76. """
  77. module = self.parse_module()
  78. if not module:
  79. raise UnknownError('Unknown module for {}.'.format(self.error))
  80. num = (((0xFF & self.RUNTIME) << 30)
  81. | ((0xFF & self.TYPE) << 28)
  82. | ((0xFF & self.LEVEL) << 25)
  83. | ((0xFF & self.SYSID) << 17)
  84. | ((0xFF & module.value) << 12)
  85. | (0x0FFF & self.error.value))
  86. return hex(num)[2:].zfill(8).upper()
  87. def __str__(self):
  88. return '[{}] code: {}, msg: {}'.format(self.__class__.__name__, self.error_code, self.message)
  89. class ParamValueError(MindInsightException):
  90. """Request param value error."""
  91. def __init__(self, error_detail):
  92. error_msg = 'Invalid parameter value. {}'.format(error_detail)
  93. super(ParamValueError, self).__init__(
  94. GeneralErrors.PARAM_VALUE_ERROR,
  95. error_msg,
  96. http_code=400)
  97. class ParamTypeError(MindInsightException):
  98. """Request param type error."""
  99. def __init__(self, param_name, expected_type):
  100. error_msg = "Invalid parameter type. '{}' expect {} type.".format(param_name, expected_type)
  101. super(ParamTypeError, self).__init__(
  102. GeneralErrors.PARAM_TYPE_ERROR,
  103. error_msg,
  104. http_code=400)
  105. class ParamMissError(MindInsightException):
  106. """Missing param error."""
  107. def __init__(self, param_name):
  108. error_msg = "Param missing. '{}' is required.".format(param_name)
  109. super(ParamMissError, self).__init__(
  110. GeneralErrors.PARAM_MISSING_ERROR,
  111. error_msg,
  112. http_code=400)
  113. class PathNotExistError(MindInsightException):
  114. """Raised when specified path do not exist."""
  115. def __init__(self, error_detail):
  116. """Initialize PathNotExistError."""
  117. error_msg = 'Specified path does not exist. Detail: {}'.format(error_detail)
  118. super(PathNotExistError, self).__init__(
  119. GeneralErrors.PATH_NOT_EXISTS_ERROR,
  120. error_msg,
  121. http_code=400)
  122. class FileSystemPermissionError(MindInsightException):
  123. """Can not access file or dir."""
  124. def __init__(self, error_detail):
  125. error_msg = 'File or dir access failed. Detail: {}'.format(error_detail)
  126. super(FileSystemPermissionError, self).__init__(
  127. GeneralErrors.FILE_SYSTEM_PERMISSION_ERROR,
  128. error_msg,
  129. http_code=400)
  130. class PortNotAvailableError(MindInsightException):
  131. """Port not available error.."""
  132. def __init__(self, error_detail):
  133. error_msg = 'Port not available error. Detail: {}'.format(error_detail)
  134. super(PortNotAvailableError, self).__init__(
  135. GeneralErrors.PORT_NOT_AVAILABLE_ERROR,
  136. error_msg,
  137. http_code=400)
  138. class UnknownError(MindInsightException):
  139. """Unknown error."""
  140. def __init__(self, error_msg):
  141. super(UnknownError, self).__init__(
  142. GeneralErrors.UNKNOWN_ERROR,
  143. error_msg,
  144. http_code=500)
  145. class UrlDecodeError(MindInsightException):
  146. """Url decoding failed"""
  147. def __init__(self, error_detail):
  148. error_msg = f"Url decode failed. Detail: {error_detail}"
  149. super(UrlDecodeError, self).__init__(GeneralErrors.URL_DECODE_ERROR,
  150. error_msg,
  151. http_code=400)