1#!/usr/bin/env python3 2# -*- coding: utf-8 -*- 3 4# 5# Copyright (c) 2023 Huawei Device Co., Ltd. 6# Licensed under the Apache License, Version 2.0 (the "License"); 7# you may not use this file except in compliance with the License. 8# You may obtain a copy of the License at 9# 10# http://www.apache.org/licenses/LICENSE-2.0 11# 12# Unless required by applicable law or agreed to in writing, software 13# distributed under the License is distributed on an "AS IS" BASIS, 14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15# See the License for the specific language governing permissions and 16# limitations under the License. 17# 18 19import os 20import traceback 21 22from exceptions.ohos_exception import OHOSException 23from util.log_util import LogUtil 24from util.io_util import IoUtil 25from resources.global_var import ROOT_CONFIG_FILE, CURRENT_OHOS_ROOT 26 27 28def throw_exception(func): 29 """Description: Function decorator that catch all exception raised by target function, 30 please DO NOT use this function directly 31 @parameter: "func": The function to be decorated 32 @return:None 33 @OHOSException: The first digit of the code represents the compilation stage, 34 '1', '2', '3', '4' corresponds to preloader, loader, gn, ninja stages respectively 35 36 Usage: 37 38 @throw_exception 39 def foo(): 40 ... 41 raise OHOSException('SOME ERROR HAPPENDED', '0000') 42 ... 43 44 """ 45 def wrapper(*args, **kwargs): 46 try: 47 return func(*args, **kwargs) 48 except OHOSException and Exception as exception: 49 _code = '' 50 _solution = '' 51 52 if isinstance(exception, OHOSException): 53 _code = exception._code 54 _solution = exception.get_solution() 55 else: 56 _code = '0000' 57 _solution = 'no solution' 58 59 _print_formatted_tracebak(_code, str(exception), _solution) 60 exit(-1) 61 return wrapper 62 63 64def _print_formatted_tracebak(_code, _exception, _solution): 65 _log_path = '' 66 if IoUtil.read_json_file(ROOT_CONFIG_FILE).get('out_path') is not None: 67 _log_path = os.path.join(IoUtil.read_json_file( 68 ROOT_CONFIG_FILE).get('out_path'), 'build.log') 69 else: 70 _log_path = os.path.join(CURRENT_OHOS_ROOT, 'out', 'build.log') 71 LogUtil.write_log(_log_path, traceback.format_exc() + '\n', 'error') 72 LogUtil.write_log(_log_path, 73 'Code: {}' 74 '\n' 75 '\n' 76 'Reason: {}' 77 '\n' 78 '\n' 79 'Solution: {}' 80 '\n' 81 '\n' 82 .format(_code, _exception, _solution), 'error') 83