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 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. """Define custom exception."""
  16. import abc
  17. import sys
  18. from enum import unique, Enum
  19. from importlib import import_module
  20. from lib2to3.pgen2 import parse
  21. from treelib.exceptions import DuplicatedNodeIdError, MultipleRootError, NodeIDAbsentError
  22. from mindinsight.mindconverter.common.log import logger as log, logger_console as log_console
  23. from mindinsight.utils.constant import ScriptConverterErrors
  24. from mindinsight.utils.exceptions import MindInsightException
  25. @unique
  26. class ConverterErrors(ScriptConverterErrors):
  27. """Converter error codes."""
  28. SCRIPT_NOT_SUPPORT = 1
  29. NODE_TYPE_NOT_SUPPORT = 2
  30. CODE_SYNTAX_ERROR = 3
  31. BASE_CONVERTER_FAIL = 000
  32. GRAPH_INIT_FAIL = 100
  33. TREE_CREATE_FAIL = 200
  34. SOURCE_FILES_SAVE_FAIL = 300
  35. GENERATOR_FAIL = 400
  36. SUB_GRAPH_SEARCHING_FAIL = 500
  37. class ScriptNotSupport(MindInsightException):
  38. """The script can not support to process."""
  39. def __init__(self, msg):
  40. super(ScriptNotSupport, self).__init__(ConverterErrors.SCRIPT_NOT_SUPPORT,
  41. msg,
  42. http_code=400)
  43. class NodeTypeNotSupport(MindInsightException):
  44. """The astNode can not support to process."""
  45. def __init__(self, msg):
  46. super(NodeTypeNotSupport, self).__init__(ConverterErrors.NODE_TYPE_NOT_SUPPORT,
  47. msg,
  48. http_code=400)
  49. class CodeSyntaxError(MindInsightException):
  50. """The CodeSyntaxError class definition."""
  51. def __init__(self, msg):
  52. super(CodeSyntaxError, self).__init__(ConverterErrors.CODE_SYNTAX_ERROR,
  53. msg,
  54. http_code=400)
  55. class MindConverterException(Exception):
  56. """MindConverter exception."""
  57. BASE_ERROR_CODE = None # ConverterErrors.BASE_CONVERTER_FAIL.value
  58. # ERROR_CODE should be declared in child exception.
  59. ERROR_CODE = None
  60. def __init__(self, **kwargs):
  61. """Initialization of MindInsightException."""
  62. user_msg = kwargs.get('user_msg', '')
  63. if isinstance(user_msg, str):
  64. user_msg = ' '.join(user_msg.split())
  65. super(MindConverterException, self).__init__()
  66. self.user_msg = user_msg
  67. self.root_exception_error_code = None
  68. def __str__(self):
  69. return '[{}] code: {}, msg: {}'.format(self.__class__.__name__, self.error_code(), self.user_msg)
  70. def __repr__(self):
  71. return self.__str__()
  72. def error_code(self):
  73. """"
  74. Calculate error code.
  75. code compose(2bytes)
  76. error: 16bits.
  77. num = 0xFFFF & error
  78. error_cods
  79. Returns:
  80. str, Hex string representing the composed MindConverter error code.
  81. """
  82. if self.root_exception_error_code:
  83. return self.root_exception_error_code
  84. if self.BASE_ERROR_CODE is None or self.ERROR_CODE is None:
  85. raise ValueError("MindConverterException has not been initialized.")
  86. num = 0xFFFF & self.ERROR_CODE # 0xFFFF & self.error.value
  87. error_code = f"{str(self.BASE_ERROR_CODE).zfill(3)}{hex(num)[2:].zfill(4).upper()}"
  88. return error_code
  89. @classmethod
  90. @abc.abstractmethod
  91. def raise_from(cls):
  92. """Raise from below exceptions."""
  93. @classmethod
  94. def uniform_catcher(cls, msg: str = ""):
  95. """Uniform exception catcher."""
  96. def decorator(func):
  97. def _f(*args, **kwargs):
  98. try:
  99. res = func(*args, **kwargs)
  100. except cls.raise_from() as e:
  101. error = cls() if not msg else cls(msg=msg)
  102. detail_info = str(e)
  103. log.error(error)
  104. log_console.error("\n")
  105. log_console.error(detail_info)
  106. log_console.error("\n")
  107. log.exception(e)
  108. sys.exit(0)
  109. except ModuleNotFoundError as e:
  110. detail_info = "Error detail: Required package not found, please check the runtime environment."
  111. log_console.error("\n")
  112. log_console.error(str(e))
  113. log_console.error(detail_info)
  114. log_console.error("\n")
  115. log.exception(e)
  116. sys.exit(0)
  117. return res
  118. return _f
  119. return decorator
  120. @classmethod
  121. def check_except(cls, msg):
  122. """Check except."""
  123. def decorator(func):
  124. def _f(*args, **kwargs):
  125. try:
  126. output = func(*args, **kwargs)
  127. except cls.raise_from() as e:
  128. error = cls(msg=msg)
  129. error_code = e.error_code() if isinstance(e, MindConverterException) else None
  130. error.root_exception_error_code = error_code
  131. log.error(msg)
  132. log.exception(e)
  133. raise error
  134. except Exception as e:
  135. log.error(msg)
  136. log.exception(e)
  137. raise e
  138. return output
  139. return _f
  140. return decorator
  141. class BaseConverterError(MindConverterException):
  142. """Base converter failed."""
  143. @unique
  144. class ErrCode(Enum):
  145. """Define error code of BaseConverterError."""
  146. UNKNOWN_ERROR = 0
  147. UNKNOWN_MODEL = 1
  148. BASE_ERROR_CODE = ConverterErrors.BASE_CONVERTER_FAIL.value
  149. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  150. DEFAULT_MSG = "Failed to start base converter."
  151. def __init__(self, msg=DEFAULT_MSG):
  152. super(BaseConverterError, self).__init__(user_msg=msg)
  153. @classmethod
  154. def raise_from(cls):
  155. """Raise from exceptions below."""
  156. except_source = Exception, cls
  157. return except_source
  158. class UnknownModelError(BaseConverterError):
  159. """The unknown model error."""
  160. ERROR_CODE = BaseConverterError.ErrCode.UNKNOWN_MODEL.value
  161. def __init__(self, msg):
  162. super(UnknownModelError, self).__init__(msg=msg)
  163. @classmethod
  164. def raise_from(cls):
  165. return cls
  166. class GraphInitError(MindConverterException):
  167. """The graph init fail error."""
  168. @unique
  169. class ErrCode(Enum):
  170. """Define error code of GraphInitError."""
  171. UNKNOWN_ERROR = 0
  172. MODEL_NOT_SUPPORT = 1
  173. TF_RUNTIME_ERROR = 2
  174. INPUT_SHAPE_ERROR = 3
  175. MI_RUNTIME_ERROR = 4
  176. BASE_ERROR_CODE = ConverterErrors.GRAPH_INIT_FAIL.value
  177. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  178. DEFAULT_MSG = "Error occurred when init graph object."
  179. def __init__(self, msg=DEFAULT_MSG):
  180. super(GraphInitError, self).__init__(user_msg=msg)
  181. @classmethod
  182. def raise_from(cls):
  183. """Raise from exceptions below."""
  184. except_source = (FileNotFoundError,
  185. ModuleNotFoundError,
  186. ModelNotSupportError,
  187. ModelLoadingError,
  188. RuntimeIntegrityError,
  189. TypeError,
  190. ZeroDivisionError,
  191. RuntimeError,
  192. cls)
  193. return except_source
  194. class TreeCreationError(MindConverterException):
  195. """The tree create fail."""
  196. @unique
  197. class ErrCode(Enum):
  198. """Define error code of TreeCreationError."""
  199. UNKNOWN_ERROR = 0
  200. NODE_INPUT_MISSING = 1
  201. TREE_NODE_INSERT_FAIL = 2
  202. BASE_ERROR_CODE = ConverterErrors.TREE_CREATE_FAIL.value
  203. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  204. DEFAULT_MSG = "Error occurred when create hierarchical tree."
  205. def __init__(self, msg=DEFAULT_MSG):
  206. super(TreeCreationError, self).__init__(user_msg=msg)
  207. @classmethod
  208. def raise_from(cls):
  209. """Raise from exceptions below."""
  210. except_source = NodeInputMissingError, TreeNodeInsertError, cls
  211. return except_source
  212. class SourceFilesSaveError(MindConverterException):
  213. """The source files save fail error."""
  214. @unique
  215. class ErrCode(Enum):
  216. """Define error code of SourceFilesSaveError."""
  217. UNKNOWN_ERROR = 0
  218. NODE_INPUT_TYPE_NOT_SUPPORT = 1
  219. SCRIPT_GENERATE_FAIL = 2
  220. REPORT_GENERATE_FAIL = 3
  221. BASE_ERROR_CODE = ConverterErrors.SOURCE_FILES_SAVE_FAIL.value
  222. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  223. DEFAULT_MSG = "Error occurred when save source files."
  224. def __init__(self, msg=DEFAULT_MSG):
  225. super(SourceFilesSaveError, self).__init__(user_msg=msg)
  226. @classmethod
  227. def raise_from(cls):
  228. """Raise from exceptions below."""
  229. except_source = (NodeInputTypeNotSupportError,
  230. ScriptGenerationError,
  231. ReportGenerationError,
  232. IOError, cls)
  233. return except_source
  234. class ModelNotSupportError(GraphInitError):
  235. """The model not support error."""
  236. ERROR_CODE = GraphInitError.ErrCode.MODEL_NOT_SUPPORT.value
  237. def __init__(self, msg):
  238. super(ModelNotSupportError, self).__init__(msg=msg)
  239. @classmethod
  240. def raise_from(cls):
  241. """Raise from exceptions below."""
  242. except_source = (RuntimeError,
  243. ModuleNotFoundError,
  244. ValueError,
  245. AssertionError,
  246. TypeError,
  247. OSError,
  248. ZeroDivisionError, cls)
  249. return except_source
  250. class TfRuntimeError(GraphInitError):
  251. """Catch tf runtime error."""
  252. ERROR_CODE = GraphInitError.ErrCode.TF_RUNTIME_ERROR.value
  253. DEFAULT_MSG = "Error occurred when init graph, TensorFlow runtime error."
  254. def __init__(self, msg=DEFAULT_MSG):
  255. super(TfRuntimeError, self).__init__(msg=msg)
  256. @classmethod
  257. def raise_from(cls):
  258. tf_error_module = import_module('tensorflow.python.framework.errors_impl')
  259. tf_error = getattr(tf_error_module, 'OpError')
  260. return tf_error, ValueError, RuntimeError, cls
  261. class RuntimeIntegrityError(GraphInitError):
  262. """Catch runtime error."""
  263. ERROR_CODE = GraphInitError.ErrCode.MI_RUNTIME_ERROR.value
  264. def __init__(self, msg):
  265. super(RuntimeIntegrityError, self).__init__(msg=msg)
  266. @classmethod
  267. def raise_from(cls):
  268. return RuntimeError, AttributeError, ImportError, ModuleNotFoundError, cls
  269. class NodeInputMissingError(TreeCreationError):
  270. """The node input missing error."""
  271. ERROR_CODE = TreeCreationError.ErrCode.NODE_INPUT_MISSING.value
  272. def __init__(self, msg):
  273. super(NodeInputMissingError, self).__init__(msg=msg)
  274. @classmethod
  275. def raise_from(cls):
  276. return ValueError, IndexError, KeyError, AttributeError, cls
  277. class TreeNodeInsertError(TreeCreationError):
  278. """The tree node create fail error."""
  279. ERROR_CODE = TreeCreationError.ErrCode.TREE_NODE_INSERT_FAIL.value
  280. def __init__(self, msg):
  281. super(TreeNodeInsertError, self).__init__(msg=msg)
  282. @classmethod
  283. def raise_from(cls):
  284. """Raise from exceptions below."""
  285. except_source = (OSError,
  286. DuplicatedNodeIdError,
  287. MultipleRootError,
  288. NodeIDAbsentError, cls)
  289. return except_source
  290. class NodeInputTypeNotSupportError(SourceFilesSaveError):
  291. """The node input type NOT support error."""
  292. ERROR_CODE = SourceFilesSaveError.ErrCode.NODE_INPUT_TYPE_NOT_SUPPORT.value
  293. def __init__(self, msg):
  294. super(NodeInputTypeNotSupportError, self).__init__(msg=msg)
  295. @classmethod
  296. def raise_from(cls):
  297. return ValueError, TypeError, IndexError, cls
  298. class ScriptGenerationError(SourceFilesSaveError):
  299. """The script generate fail error."""
  300. ERROR_CODE = SourceFilesSaveError.ErrCode.SCRIPT_GENERATE_FAIL.value
  301. def __init__(self, msg):
  302. super(ScriptGenerationError, self).__init__(msg=msg)
  303. @classmethod
  304. def raise_from(cls):
  305. """Raise from exceptions below."""
  306. except_source = (RuntimeError,
  307. parse.ParseError,
  308. AttributeError, cls)
  309. return except_source
  310. class ReportGenerationError(SourceFilesSaveError):
  311. """The report generate fail error."""
  312. ERROR_CODE = SourceFilesSaveError.ErrCode.REPORT_GENERATE_FAIL.value
  313. def __init__(self, msg):
  314. super(ReportGenerationError, self).__init__(msg=msg)
  315. @classmethod
  316. def raise_from(cls):
  317. """Raise from exceptions below."""
  318. return ZeroDivisionError, cls
  319. class SubGraphSearchingError(MindConverterException):
  320. """Sub-graph searching exception."""
  321. @unique
  322. class ErrCode(Enum):
  323. """Define error code of SourceFilesSaveError."""
  324. BASE_ERROR = 0
  325. CANNOT_FIND_VALID_PATTERN = 1
  326. MODEL_NOT_SUPPORT = 2
  327. BASE_ERROR_CODE = ConverterErrors.SUB_GRAPH_SEARCHING_FAIL.value
  328. ERROR_CODE = ErrCode.BASE_ERROR.value
  329. DEFAULT_MSG = "Sub-Graph pattern searching fail."
  330. def __init__(self, msg=DEFAULT_MSG):
  331. super(SubGraphSearchingError, self).__init__(user_msg=msg)
  332. @classmethod
  333. def raise_from(cls):
  334. """Define exception in sub-graph searching module."""
  335. return IndexError, KeyError, ValueError, AttributeError, ZeroDivisionError, cls
  336. class GeneratorError(MindConverterException):
  337. """The Generator fail error."""
  338. @unique
  339. class ErrCode(Enum):
  340. """Define error code of SourceFilesSaveError."""
  341. BASE_ERROR = 0
  342. STATEMENT_GENERATION_ERROR = 1
  343. CONVERTED_OPERATOR_LOADING_ERROR = 2
  344. BASE_ERROR_CODE = ConverterErrors.GENERATOR_FAIL.value
  345. ERROR_CODE = ErrCode.BASE_ERROR.value
  346. DEFAULT_MSG = "Error occurred when generate code."
  347. def __init__(self, msg=DEFAULT_MSG):
  348. super(GeneratorError, self).__init__(user_msg=msg)
  349. @classmethod
  350. def raise_from(cls):
  351. """Raise from exceptions below."""
  352. except_source = (ValueError, TypeError, cls)
  353. return except_source
  354. class ModelLoadingError(GraphInitError):
  355. """Model loading fail."""
  356. ERROR_CODE = GraphInitError.ErrCode.INPUT_SHAPE_ERROR.value
  357. def __init__(self, msg):
  358. super(ModelLoadingError, self).__init__(msg=msg)
  359. @classmethod
  360. def raise_from(cls):
  361. """Define exception when model loading fail."""
  362. return ValueError, cls