• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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"""
16Define custom exception
17
18Error rule:
19    EXCEPTIONS key: The error code key should be as same as the realized class name.
20     exception No: common module error No is 1-99,
21                        unknown error No is 0,
22                    shard* api error No is 100-199
23                    file* api error No is 200-299
24     error message: It is the base error message.
25                    You can recover error message in realized class __init__ function.
26"""
27from .enums import LogRuntime, ErrorCodeType, ErrorLevel
28from .constant import SYS_ID
29EXCEPTIONS = dict(
30    # the format of list is [exception No, base error message]
31    UnknownError=[0, 'Unknown Error.'],
32    ParamTypeError=[1, 'Param type is error.'],
33    ParamValueError=[2, 'Param value is error.'],
34    ParamMissError=[3, 'Param missing.'],
35    PathNotExistsError=[4, 'Path does not exist.'],
36    DbConnectionError=[5, 'Db connection is error.'],
37
38    # MindRecord error 100-199 for shard*
39    MRMOpenError=[100, 'MindRecord could not open.'],
40    MRMOpenForAppendError=[101, 'MindRecord could not open for append.'],
41    MRMInvalidPageSizeError=[102, 'Failed to set page size.'],
42    MRMInvalidHeaderSizeError=[103, 'Failed to set header size.'],
43    MRMSetHeaderError=[104, 'Failed to set header.'],
44    MRMWriteDatasetError=[105, 'Failed to write dataset.'],
45    MRMCommitError=[107, 'Failed to commit.'],
46
47    MRMLaunchError=[108, 'Failed to launch.'],
48    MRMFinishError=[109, 'Failed to finish.'],
49    MRMCloseError=[110, 'Failed to close.'],
50
51    MRMAddSchemaError=[111, 'Failed to add schema.'],
52    MRMAddIndexError=[112, 'Failed to add index field.'],
53    MRMBuildSchemaError=[113, 'Failed to build schema.'],
54    MRMGetMetaError=[114, 'Failed to get meta info.'],
55
56    MRMIndexGeneratorError=[115, 'Failed to create index generator.'],
57    MRMGenerateIndexError=[116, 'Failed to generate index.'],
58
59    MRMInitSegmentError=[117, 'Failed to initialize segment.'],
60    MRMFetchCandidateFieldsError=[118, 'Failed to fetch candidate category fields.'],
61    MRMReadCategoryInfoError=[119, 'Failed to read category information.'],
62    MRMFetchDataError=[120, 'Failed to fetch data by category.'],
63
64
65    # MindRecord error 200-299 for File* and MindPage
66    MRMInvalidSchemaError=[200, 'Schema is error.'],
67    MRMValidateDataError=[201, 'Raw data is valid.'],
68    MRMDefineIndexError=[202, 'Index field is error.'],
69    MRMDefineBlobError=[203, 'Blob field is error.'],
70    MRMUnsupportedSchemaError=[204, 'Schema is not supported.'],
71    MRMDefineCategoryError=[205, 'Category field is error.'],
72
73)
74
75
76class MindRecordException(Exception):
77    """MindRecord base error class."""
78
79    def __init__(self):
80        """Initialize an error which may occurs in mindrecord."""
81        super(MindRecordException, self).__init__()
82        class_name = self.__class__.__name__
83        error_item = EXCEPTIONS[class_name] if class_name in EXCEPTIONS \
84            else EXCEPTIONS['UnknownError']
85        self._error_msg = error_item[1]
86        self._error_code = MindRecordException.transform_error_code(error_item[0])
87
88    @property
89    def error_msg(self):
90        """return the description of this error."""
91        return self._error_msg
92
93    @error_msg.setter
94    def error_msg(self, msg):
95        self._error_msg = msg
96
97    @property
98    def error_code(self):
99        """return the unique error number of this error."""
100        return self._error_code
101
102    def __str__(self):
103        return "[{}]: {}".format(self.__class__.__name__, self._error_msg)
104
105    @staticmethod
106    def transform_error_code(exception_no):
107        """
108        Transform mindrecord exception no to GE error code.
109
110        error_code = ((0xFF & runtime) << 30) \
111                    | ((0xFF & error_code_type) << 28) \
112                    | ((0xFF & error_level) << 25) \
113                    | ((0xFF & sys_id) << 17) \
114                    | ((0xFF & mod_id) << 12) \
115                    | (0x0FFF & exception_no)
116        Args:
117            exception_no: Integer. Exception number.
118
119        Returns:
120            Integer, error code.
121
122        """
123        runtime = LogRuntime.RT_HOST
124        error_code_type = ErrorCodeType.ERROR_CODE
125        error_level = ErrorLevel.COMMON_LEVEL
126        exception_no_range_per_module = 100
127        mod_id = int(exception_no / exception_no_range_per_module) + 1
128        error_code = (((0xFF & runtime) << 30)
129                      | ((0xFF & error_code_type) << 28)
130                      | ((0xFF & error_level) << 25)
131                      | ((0xFF & SYS_ID) << 17)
132                      | ((0xFF & mod_id) << 12)
133                      | (0x0FFF & exception_no))
134        return error_code
135
136
137class UnknownError(MindRecordException):
138    """Raise an unknown error when an unknown error occurs."""
139
140
141class ParamValueError(MindRecordException):
142    """
143    Request param value error.
144    """
145
146    def __init__(self, error_detail):
147        super(ParamValueError, self).__init__()
148        self.error_msg = 'Invalid parameter value. {}'.format(error_detail)
149
150
151class ParamTypeError(MindRecordException):
152    """
153    Request param type error.
154    """
155
156    def __init__(self, param_name, expected_type):
157        super(ParamTypeError, self).__init__()
158        self.error_msg = "Invalid parameter type. '{}' expect {} type." \
159                         "".format(param_name, expected_type)
160
161
162class ParamMissError(MindRecordException):
163    """
164    missing param error.
165    """
166
167    def __init__(self, param_name):
168        super(ParamMissError, self).__init__()
169        self.error_msg = "Param missing. '{}' is required.".format(param_name)
170
171
172class PathNotExistsError(MindRecordException):
173    """
174    invalid path.
175    """
176    def __init__(self, error_path):
177        super(PathNotExistsError, self).__init__()
178        self.error_msg = 'Invalid path. {}'.format(error_path)
179
180
181class DbConnectionError(MindRecordException):
182    """
183    Database connection error.
184    """
185    def __init__(self, error_detail):
186        super(DbConnectionError, self).__init__()
187        self.error_msg = 'Db connection is error. Detail: {}'.format(error_detail)
188
189
190class MRMOpenError(MindRecordException):
191    """
192    Raised when could not open mind record file successfully.
193    """
194    def __init__(self):
195        super(MRMOpenError, self).__init__()
196        self.error_msg = 'MindRecord File could not open successfully.'
197
198
199class MRMOpenForAppendError(MindRecordException):
200    """
201    Raised when could not open mind record file successfully for append.
202    """
203    def __init__(self):
204        super(MRMOpenForAppendError, self).__init__()
205        self.error_msg = 'MindRecord File could not open successfully for append.'
206
207
208class MRMInvalidPageSizeError(MindRecordException):
209    pass
210
211
212class MRMInvalidHeaderSizeError(MindRecordException):
213    pass
214
215
216class MRMSetHeaderError(MindRecordException):
217    pass
218
219
220class MRMWriteDatasetError(MindRecordException):
221    pass
222
223
224class MRMCommitError(MindRecordException):
225    pass
226
227
228class MRMLaunchError(MindRecordException):
229    pass
230
231
232class MRMFinishError(MindRecordException):
233    pass
234
235
236class MRMCloseError(MindRecordException):
237    pass
238
239
240class MRMAddSchemaError(MindRecordException):
241    pass
242
243
244class MRMAddIndexError(MindRecordException):
245    pass
246
247
248class MRMBuildSchemaError(MindRecordException):
249    pass
250
251
252class MRMGetMetaError(MindRecordException):
253    pass
254
255
256class MRMIndexGeneratorError(MindRecordException):
257    pass
258
259
260class MRMGenerateIndexError(MindRecordException):
261    pass
262
263
264class MRMInitSegmentError(MindRecordException):
265    pass
266
267
268class MRMFetchCandidateFieldsError(MindRecordException):
269    pass
270
271
272class MRMReadCategoryInfoError(MindRecordException):
273    pass
274
275
276class MRMFetchDataError(MindRecordException):
277    pass
278
279
280class MRMInvalidSchemaError(MindRecordException):
281    def __init__(self, error_detail):
282        super(MRMInvalidSchemaError, self).__init__()
283        self.error_msg = 'Schema format is error. Detail: {}'.format(error_detail)
284
285
286class MRMValidateDataError(MindRecordException):
287    def __init__(self, error_detail):
288        super(MRMValidateDataError, self).__init__()
289        self.error_msg = 'Raw data do not match the schema. Detail: {}'.format(error_detail)
290
291
292class MRMDefineIndexError(MindRecordException):
293    def __init__(self, error_detail):
294        super(MRMDefineIndexError, self).__init__()
295        self.error_msg = 'Failed to define index field. Detail: {}'.format(error_detail)
296
297
298class MRMDefineBlobError(MindRecordException):
299    def __init__(self, error_detail):
300        super(MRMDefineBlobError, self).__init__()
301        self.error_msg = 'Failed to define blob field. Detail: {}'.format(error_detail)
302
303
304class MRMUnsupportedSchemaError(MindRecordException):
305    def __init__(self, error_detail):
306        super(MRMUnsupportedSchemaError, self).__init__()
307        self.error_msg = 'Schema is not supported. Detail: {}'.format(error_detail)
308
309
310class MRMDefineCategoryError(MindRecordException):
311    def __init__(self, error_detail):
312        super(MRMDefineCategoryError, self).__init__()
313        self.error_msg = 'Failed to define category field. Detail: {}'.format(error_detail)
314