1/* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 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 16import { common } from '@kit.AbilityKit'; 17import Constants from '../../common/constant'; 18import { ResultMsg } from '../../common/ResultMsg'; 19import Result from '../../common/Result'; 20import OpeningDialogManager from '../manager/OpeningDialogManager'; 21import { HiLog } from '../../common/HiLog'; 22import { BusinessError } from '@ohos.base'; 23import { ErrorHandlerFactory } from '../manager/ErrorManager'; 24 25const TAG = 'ErrorHandler'; 26 27export default class ErrorHandler { 28 private static instance: ErrorHandler; 29 private errorInfo?: BusinessError; 30 31 private constructor() { 32 } 33 34 static getInstance(): ErrorHandler { 35 if (!ErrorHandler.instance) { 36 ErrorHandler.instance = new ErrorHandler(); 37 } 38 return ErrorHandler.instance; 39 } 40 41 // 弹框超过250ms,弹toast;弹框小于250ms,等待弹框250ms之后,弹toast 42 public async startHandleError(requestId: string, error?: BusinessError): Promise<Result<boolean>> { 43 HiLog.info(TAG, `start startErrorHandler requestId ${requestId}`); 44 if (error) { 45 this.errorInfo = error; 46 } 47 if (!this.errorInfo) { 48 HiLog.error(TAG, 'errorInfo null'); 49 return ResultMsg.getErrMsg(Constants.ERR_CODE_PARAMS_CHECK_ERROR); 50 } 51 const viewContext = AppStorage.get('viewContext') as common.ServiceExtensionContext; 52 if (!viewContext) { 53 HiLog.error(TAG, 'viewContext null'); 54 return ResultMsg.getErrMsg(Constants.ERR_CODE_PARAMS_CHECK_ERROR); 55 } 56 57 const canShowToast = OpeningDialogManager.getInstance().getCanShowToast(); 58 HiLog.info(TAG, `startHandleError canShowToast ${canShowToast}`); 59 60 if (!canShowToast) { 61 HiLog.error(TAG, 'canShowToast error'); 62 OpeningDialogManager.getInstance().setIsWaitingShowToast(true); 63 return ResultMsg.buildSuccess(); 64 } 65 OpeningDialogManager.getInstance().deleteRequestId(requestId); 66 OpeningDialogManager.getInstance().setIsWaitingShowToast(false); 67 68 await this.startHandleErrorInner(this.errorInfo); 69 this.errorInfo = undefined; 70 return ResultMsg.buildSuccess(); 71 } 72 73 private async startHandleErrorInner(error: BusinessError): Promise<void> { 74 HiLog.info(TAG, 'startHandleErrorInner'); 75 const errorHandle = ErrorHandlerFactory.createErrorHandle(); 76 await errorHandle.handle(error); 77 } 78}