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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. PARAM_MISSING = 2
  149. BASE_ERROR_CODE = ConverterErrors.BASE_CONVERTER_FAIL.value
  150. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  151. DEFAULT_MSG = "Failed to start base converter."
  152. def __init__(self, msg=DEFAULT_MSG):
  153. super(BaseConverterError, self).__init__(user_msg=msg)
  154. @classmethod
  155. def raise_from(cls):
  156. """Raise from exceptions below."""
  157. except_source = Exception, UnknownModelError, ParamMissingError, cls
  158. return except_source
  159. class UnknownModelError(BaseConverterError):
  160. """The unknown model error."""
  161. ERROR_CODE = BaseConverterError.ErrCode.UNKNOWN_MODEL.value
  162. def __init__(self, msg):
  163. super(UnknownModelError, self).__init__(msg=msg)
  164. @classmethod
  165. def raise_from(cls):
  166. return cls
  167. class ParamMissingError(BaseConverterError):
  168. """Define cli params missing error."""
  169. ERROR_CODE = BaseConverterError.ErrCode.PARAM_MISSING.value
  170. def __init__(self, msg):
  171. super(ParamMissingError, self).__init__(msg=msg)
  172. @classmethod
  173. def raise_from(cls):
  174. return cls
  175. class GraphInitError(MindConverterException):
  176. """The graph init fail error."""
  177. @unique
  178. class ErrCode(Enum):
  179. """Define error code of GraphInitError."""
  180. UNKNOWN_ERROR = 0
  181. MODEL_NOT_SUPPORT = 1
  182. TF_RUNTIME_ERROR = 2
  183. INPUT_SHAPE_ERROR = 3
  184. MI_RUNTIME_ERROR = 4
  185. BASE_ERROR_CODE = ConverterErrors.GRAPH_INIT_FAIL.value
  186. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  187. DEFAULT_MSG = "Error occurred when init graph object."
  188. def __init__(self, msg=DEFAULT_MSG):
  189. super(GraphInitError, self).__init__(user_msg=msg)
  190. @classmethod
  191. def raise_from(cls):
  192. """Raise from exceptions below."""
  193. except_source = (FileNotFoundError,
  194. ModuleNotFoundError,
  195. ModelNotSupportError,
  196. ModelLoadingError,
  197. RuntimeIntegrityError,
  198. TypeError,
  199. ZeroDivisionError,
  200. RuntimeError,
  201. cls)
  202. return except_source
  203. class TreeCreationError(MindConverterException):
  204. """The tree create fail."""
  205. @unique
  206. class ErrCode(Enum):
  207. """Define error code of TreeCreationError."""
  208. UNKNOWN_ERROR = 0
  209. NODE_INPUT_MISSING = 1
  210. TREE_NODE_INSERT_FAIL = 2
  211. BASE_ERROR_CODE = ConverterErrors.TREE_CREATE_FAIL.value
  212. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  213. DEFAULT_MSG = "Error occurred when create hierarchical tree."
  214. def __init__(self, msg=DEFAULT_MSG):
  215. super(TreeCreationError, self).__init__(user_msg=msg)
  216. @classmethod
  217. def raise_from(cls):
  218. """Raise from exceptions below."""
  219. except_source = NodeInputMissingError, TreeNodeInsertError, cls
  220. return except_source
  221. class SourceFilesSaveError(MindConverterException):
  222. """The source files save fail error."""
  223. @unique
  224. class ErrCode(Enum):
  225. """Define error code of SourceFilesSaveError."""
  226. UNKNOWN_ERROR = 0
  227. NODE_INPUT_TYPE_NOT_SUPPORT = 1
  228. SCRIPT_GENERATE_FAIL = 2
  229. REPORT_GENERATE_FAIL = 3
  230. BASE_ERROR_CODE = ConverterErrors.SOURCE_FILES_SAVE_FAIL.value
  231. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  232. DEFAULT_MSG = "Error occurred when save source files."
  233. def __init__(self, msg=DEFAULT_MSG):
  234. super(SourceFilesSaveError, self).__init__(user_msg=msg)
  235. @classmethod
  236. def raise_from(cls):
  237. """Raise from exceptions below."""
  238. except_source = (NodeInputTypeNotSupportError,
  239. ScriptGenerationError,
  240. ReportGenerationError,
  241. IOError, cls)
  242. return except_source
  243. class ModelNotSupportError(GraphInitError):
  244. """The model not support error."""
  245. ERROR_CODE = GraphInitError.ErrCode.MODEL_NOT_SUPPORT.value
  246. def __init__(self, msg):
  247. super(ModelNotSupportError, self).__init__(msg=msg)
  248. @classmethod
  249. def raise_from(cls):
  250. """Raise from exceptions below."""
  251. except_source = (RuntimeError,
  252. ModuleNotFoundError,
  253. ValueError,
  254. AssertionError,
  255. TypeError,
  256. OSError,
  257. ZeroDivisionError, cls)
  258. return except_source
  259. class TfRuntimeError(GraphInitError):
  260. """Catch tf runtime error."""
  261. ERROR_CODE = GraphInitError.ErrCode.TF_RUNTIME_ERROR.value
  262. DEFAULT_MSG = "Error occurred when init graph, TensorFlow runtime error."
  263. def __init__(self, msg=DEFAULT_MSG):
  264. super(TfRuntimeError, self).__init__(msg=msg)
  265. @classmethod
  266. def raise_from(cls):
  267. tf_error_module = import_module('tensorflow.python.framework.errors_impl')
  268. tf_error = getattr(tf_error_module, 'OpError')
  269. return tf_error, ValueError, RuntimeError, cls
  270. class RuntimeIntegrityError(GraphInitError):
  271. """Catch runtime error."""
  272. ERROR_CODE = GraphInitError.ErrCode.MI_RUNTIME_ERROR.value
  273. def __init__(self, msg):
  274. super(RuntimeIntegrityError, self).__init__(msg=msg)
  275. @classmethod
  276. def raise_from(cls):
  277. return RuntimeError, AttributeError, ImportError, ModuleNotFoundError, cls
  278. class NodeInputMissingError(TreeCreationError):
  279. """The node input missing error."""
  280. ERROR_CODE = TreeCreationError.ErrCode.NODE_INPUT_MISSING.value
  281. def __init__(self, msg):
  282. super(NodeInputMissingError, self).__init__(msg=msg)
  283. @classmethod
  284. def raise_from(cls):
  285. return ValueError, IndexError, KeyError, AttributeError, cls
  286. class TreeNodeInsertError(TreeCreationError):
  287. """The tree node create fail error."""
  288. ERROR_CODE = TreeCreationError.ErrCode.TREE_NODE_INSERT_FAIL.value
  289. def __init__(self, msg):
  290. super(TreeNodeInsertError, self).__init__(msg=msg)
  291. @classmethod
  292. def raise_from(cls):
  293. """Raise from exceptions below."""
  294. except_source = (OSError,
  295. DuplicatedNodeIdError,
  296. MultipleRootError,
  297. NodeIDAbsentError, cls)
  298. return except_source
  299. class NodeInputTypeNotSupportError(SourceFilesSaveError):
  300. """The node input type NOT support error."""
  301. ERROR_CODE = SourceFilesSaveError.ErrCode.NODE_INPUT_TYPE_NOT_SUPPORT.value
  302. def __init__(self, msg):
  303. super(NodeInputTypeNotSupportError, self).__init__(msg=msg)
  304. @classmethod
  305. def raise_from(cls):
  306. return ValueError, TypeError, IndexError, cls
  307. class ScriptGenerationError(SourceFilesSaveError):
  308. """The script generate fail error."""
  309. ERROR_CODE = SourceFilesSaveError.ErrCode.SCRIPT_GENERATE_FAIL.value
  310. def __init__(self, msg):
  311. super(ScriptGenerationError, self).__init__(msg=msg)
  312. @classmethod
  313. def raise_from(cls):
  314. """Raise from exceptions below."""
  315. except_source = (RuntimeError,
  316. parse.ParseError,
  317. AttributeError, cls)
  318. return except_source
  319. class ReportGenerationError(SourceFilesSaveError):
  320. """The report generate fail error."""
  321. ERROR_CODE = SourceFilesSaveError.ErrCode.REPORT_GENERATE_FAIL.value
  322. def __init__(self, msg):
  323. super(ReportGenerationError, self).__init__(msg=msg)
  324. @classmethod
  325. def raise_from(cls):
  326. """Raise from exceptions below."""
  327. return ZeroDivisionError, cls
  328. class SubGraphSearchingError(MindConverterException):
  329. """Sub-graph searching exception."""
  330. @unique
  331. class ErrCode(Enum):
  332. """Define error code of SourceFilesSaveError."""
  333. BASE_ERROR = 0
  334. CANNOT_FIND_VALID_PATTERN = 1
  335. MODEL_NOT_SUPPORT = 2
  336. BASE_ERROR_CODE = ConverterErrors.SUB_GRAPH_SEARCHING_FAIL.value
  337. ERROR_CODE = ErrCode.BASE_ERROR.value
  338. DEFAULT_MSG = "Sub-Graph pattern searching fail."
  339. def __init__(self, msg=DEFAULT_MSG):
  340. super(SubGraphSearchingError, self).__init__(user_msg=msg)
  341. @classmethod
  342. def raise_from(cls):
  343. """Define exception in sub-graph searching module."""
  344. return IndexError, KeyError, ValueError, AttributeError, ZeroDivisionError, cls
  345. class GeneratorError(MindConverterException):
  346. """The Generator fail error."""
  347. @unique
  348. class ErrCode(Enum):
  349. """Define error code of SourceFilesSaveError."""
  350. BASE_ERROR = 0
  351. STATEMENT_GENERATION_ERROR = 1
  352. CONVERTED_OPERATOR_LOADING_ERROR = 2
  353. BASE_ERROR_CODE = ConverterErrors.GENERATOR_FAIL.value
  354. ERROR_CODE = ErrCode.BASE_ERROR.value
  355. DEFAULT_MSG = "Error occurred when generate code."
  356. def __init__(self, msg=DEFAULT_MSG):
  357. super(GeneratorError, self).__init__(user_msg=msg)
  358. @classmethod
  359. def raise_from(cls):
  360. """Raise from exceptions below."""
  361. except_source = (ValueError, TypeError, cls)
  362. return except_source
  363. class ModelLoadingError(GraphInitError):
  364. """Model loading fail."""
  365. ERROR_CODE = GraphInitError.ErrCode.INPUT_SHAPE_ERROR.value
  366. def __init__(self, msg):
  367. super(ModelLoadingError, self).__init__(msg=msg)
  368. @classmethod
  369. def raise_from(cls):
  370. """Define exception when model loading fail."""
  371. return ValueError, cls