异常捕获增强

Signed-off-by: he-qianbei <heqianbei@huawei.com>
This commit is contained in:
he-qianbei 2024-11-05 16:54:08 +08:00
parent fa55d9fcb3
commit e90cff5d49
12 changed files with 241 additions and 107 deletions

View File

@ -2,8 +2,8 @@
"app": {
"bundleName": "com.ohos.dlpmanager",
"vendor": "example",
"versionCode": 1000120,
"versionName": "1.0.1.20",
"versionCode": 1000121,
"versionName": "1.0.1.21",
"icon": "$media:app_icon",
"label": "$string:app_name",
"minAPIVersion": 12,

View File

@ -16,8 +16,8 @@
"app": {
"bundleName": "com.ohos.dlpmanager",
"vendor": "example",
"versionCode": 1000120,
"versionName": "1.0.1.20",
"versionCode": 1000121,
"versionName": "1.0.1.21",
"icon": "$media:app_icon",
"label": "$string:app_name",
"minAPIVersion": 12,

View File

@ -273,7 +273,12 @@ export default class SaveAsAbility extends UIAbility {
offset: 0,
length: HEAD_LENGTH_IN_BYTE
};
let num = fs.readSync(srcFd, z, option);
try {
fs.readSync(srcFd, z, option);
} catch (error) {
HiLog.error(TAG, `readSync exception, error is ${JSON.stringify(error)}`);
return;
}
let buf = new Uint32Array(z, 0, HEAD_LENGTH_IN_U32);
let magic = buf[0];
@ -284,12 +289,17 @@ export default class SaveAsAbility extends UIAbility {
offset: 0,
length: txtOffset
};
num = fs.readSync(srcFd, head, option);
let buf2 = new Uint32Array(head, 0, HEAD_LENGTH_IN_U32);
buf2[SIZE_OFFSET] = 0;
num = fs.writeSync(dstFd, head, option);
resolve(true);
return;
try {
fs.readSync(srcFd, head, option);
let buf2 = new Uint32Array(head, 0, HEAD_LENGTH_IN_U32);
buf2[SIZE_OFFSET] = 0;
fs.writeSync(dstFd, head, option);
resolve(true);
return;
} catch (error) {
HiLog.error(TAG, `readSync or writeSync exception, error is ${JSON.stringify(error)}`);
return;
}
}
try {
@ -324,10 +334,10 @@ export default class SaveAsAbility extends UIAbility {
if (uri == undefined) {
return true;
}
let uriObj = new fileUri.FileUri(uri);
let dirUri = uriObj.getFullDirectoryUri(); // get directory path of a uri
let file: fs.File | undefined = undefined;
try {
let uriObj = new fileUri.FileUri(uri);
let dirUri = uriObj.getFullDirectoryUri(); // get directory path of a uri
file = fs.openSync(dirUri, fs.OpenMode.READ_ONLY);
let stat = fs.statSync(file.fd);
let isDir = stat.isDirectory();

View File

@ -119,7 +119,11 @@ export default class ViewAbility extends ServiceExtensionAbility {
GlobalContext.load('sandbox2linkFile') as Map<string, (number | string | dlpPermission.DLPFile)[][]>;
HiLog.debug(TAG, `sandbox2linkFile size: ${sandbox2linkFile.size}`);
if (sandbox2linkFile.size === 0) {
this.context.terminateSelf();
try {
this.context.terminateSelf();
} catch (error) {
HiLog.error(TAG, `terminateSelf exception, error is ${JSON.stringify(error)}`);
}
}
reject();
return;

View File

@ -16,6 +16,7 @@
import Constants from '../constant';
import common from '@ohos.app.ability.common';
import { SystemUtils } from '../systemUtils';
import { HiLog } from '../HiLog';
const TAG = '[DLPManager_dialog]';
@ -74,7 +75,11 @@ struct DlpAlertDialog {
if (this.action != null) {
this.action()
} else {
(getContext(this) as common.UIAbilityContext).terminateSelf();
try {
(getContext(this) as common.UIAbilityContext).terminateSelf();
} catch (error) {
HiLog.error(TAG, `terminateSelf exception, error is ${JSON.stringify(error)}`);
}
}
})
.margin({
@ -90,7 +95,11 @@ struct DlpAlertDialog {
.backgroundColor($r('sys.color.ohos_id_color_text_primary_activated'))
.controlSize(ControlSize.NORMAL)
.onClick(async (event) => {
(getContext(this) as common.UIAbilityContext).terminateSelf();
try {
(getContext(this) as common.UIAbilityContext).terminateSelf();
} catch (error) {
HiLog.error(TAG, `terminateSelf exception, error is ${JSON.stringify(error)}`);
}
})
.margin({
right: SystemUtils.isRTL() ?

View File

@ -87,17 +87,22 @@ export default class ConnectService {
}
searchUserInfo(remote: rpc.IRemoteObject) {
if (remote === null) {
HiLog.info(TAG, `onConnect remote is null.`);
return;
}
let cloudPhone: string | undefined = AppStorage.get('cloudPhone');
HiLog.info(TAG, `searchUserInfo start`);
let option = new rpc.MessageOption(Constants.TF_ASYNC);
let data = new rpc.MessageSequence();
let reply = new rpc.MessageSequence();
data.writeInterfaceToken('OHOS.HapDlpCredAbilityServiceStub');
let callback: CredCallbackStub = new CredCallbackStub('CredCallbackStub');
data.writeRemoteObject(callback.asObject());
data.writeString(JSON.stringify({'phone': cloudPhone}));
if (remote === null) {
HiLog.info(TAG, `onConnect remote is null.`);
try {
data.writeInterfaceToken('OHOS.HapDlpCredAbilityServiceStub');
let callback: CredCallbackStub = new CredCallbackStub('CredCallbackStub');
data.writeRemoteObject(callback.asObject());
data.writeString(JSON.stringify({'phone': cloudPhone}));
} catch (error) {
HiLog.error(TAG, `prepare data exception, error is ${JSON.stringify(error)}`);
return;
}
remote.sendMessageRequest(Constants.COMMAND_SEARCH_USER_INFO, data, reply, option).then((result) => {
@ -109,14 +114,19 @@ export default class ConnectService {
getAccountInfo(remote: rpc.IRemoteObject) {
HiLog.info(TAG, `getAccountInfo start`);
if (remote === null) {
HiLog.info(TAG, `onConnect remote is null.`);
return;
}
let option = new rpc.MessageOption(Constants.TF_ASYNC);
let data = new rpc.MessageSequence();
let reply = new rpc.MessageSequence();
data.writeInterfaceToken('OHOS.HapDlpCredAbilityServiceStub');
let callback: CredCallbackStub = new CredCallbackStub('CredCallbackStub');
data.writeRemoteObject(callback.asObject());
if (remote === null) {
HiLog.info(TAG, `onConnect remote is null.`);
try {
data.writeInterfaceToken('OHOS.HapDlpCredAbilityServiceStub');
let callback: CredCallbackStub = new CredCallbackStub('CredCallbackStub');
data.writeRemoteObject(callback.asObject());
} catch (error) {
HiLog.error(TAG, `prepare data exception, error is ${JSON.stringify(error)}`);
return;
}
remote.sendMessageRequest(Constants.COMMAND_GET_ACCOUNT_INFO, data, reply, option).then((result) => {

View File

@ -34,15 +34,26 @@ export default class CredCallbackStub extends rpc.RemoteObject {
async onRemoteMessageRequest(code: number, data: rpc.MessageSequence): Promise<boolean> {
HiLog.info(TAG, `onRemoteMessageRequest called, code = ${code}`);
if (data.readInterfaceToken() !== CredCallbackStub.DESCRIPTOR) {
HiLog.info(TAG, `DESCRIPTOR unmatched.`);
try {
if (data.readInterfaceToken() !== CredCallbackStub.DESCRIPTOR) {
HiLog.info(TAG, `DESCRIPTOR unmatched.`);
return false;
}
} catch (error) {
HiLog.error(TAG, `read data exception, error is ${JSON.stringify(error)}`);
return false;
}
switch (code) {
case Constants.COMMAND_SEARCH_USER_INFO: {
let storage = LocalStorage.getShared();
HiLog.info(TAG, `onRemoteMessageRequest command search user info`);
let resultVar = data.readString();
let resultVar = '';
try {
resultVar = data.readString();
} catch (error) {
HiLog.error(TAG, `read string exception, error is ${JSON.stringify(error)}`);
return false;
}
storage.setOrCreate('commandSearchUserInfo', resultVar);
this.connectService.disconnectServiceShareAbility();
return true;
@ -50,7 +61,13 @@ export default class CredCallbackStub extends rpc.RemoteObject {
case Constants.COMMAND_GET_ACCOUNT_INFO: {
let storage = LocalStorage.getShared();
HiLog.info(TAG, `onRemoteMessageRequest command get account info`);
let resultVar = data.readString();
let resultVar = '';
try {
resultVar = data.readString();
} catch (error) {
HiLog.error(TAG, `read string exception, error is ${JSON.stringify(error)}`);
return false;
}
storage.setOrCreate('commandGetAccountInfo', resultVar);
this.connectService.disconnectServiceShareAbility();
return true;

View File

@ -177,17 +177,28 @@ function terminateSelfWithResult(resultCode: number, result: string): void {
}
}
};
(getContext() as common.UIAbilityContext).terminateSelfWithResult(abilityResult);
try {
(getContext() as common.UIAbilityContext).terminateSelfWithResult(abilityResult);
} catch (error) {
HiLog.error(TAG, `terminateSelfWithResult exception, error is ${JSON.stringify(error)}`);
}
}
function judgeIsSandBox(want: Want) {
return new Promise<boolean>(async resolve => {
let callerToken: number = want.parameters?.['ohos.aafwk.param.callerToken'] as number;
let callerBundleName: string = want.parameters?.['ohos.aafwk.param.callerBundleName'] as string;
let applicationInfo = await bundleManager.getApplicationInfo(
callerBundleName, bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT);
if (callerToken === applicationInfo.accessTokenId) {
try {
let applicationInfo = await bundleManager.getApplicationInfo(
callerBundleName, bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT);
if (callerToken === applicationInfo.accessTokenId) {
resolve(false);
return;
}
} catch (error) {
HiLog.error(TAG, `getApplicationInfo exception, error is ${JSON.stringify(error)}`);
resolve(false);
return;
}
resolve(true);
})
@ -433,7 +444,13 @@ function getAccountType(
return new Promise(async (resolve, reject) => {
let z = new ArrayBuffer(HEAD_LENGTH_IN_BYTE);
let option: ChangeOption = { offset: 0, length: HEAD_LENGTH_IN_BYTE };
let num = fs.readSync(fd, z, option);
try {
fs.readSync(fd, z, option);
} catch (error) {
HiLog.error(TAG, `readSync exception, error is ${JSON.stringify(error)}`);
reject();
return;
}
let buf = new Uint32Array(z, 0, HEAD_LENGTH_IN_U32);
if (buf && buf[0] === Constants.DLP_ZIP_MAGIC) {
let random = String(Math.random()).substring(Constants.RAND_START, Constants.RAND_END);
@ -463,8 +480,8 @@ function getAccountType(
} else {
let cert = new ArrayBuffer(buf[CERT_SIZE]);
option = { offset: buf[CERT_OFFSET], length: buf[CERT_SIZE] };
num = fs.readSync(fd, cert, option);
try {
fs.readSync(fd, cert, option);
let textDecoder: util.TextDecoder = util.TextDecoder.create('utf-8');
let fdString: string = textDecoder.decodeWithStream(new Uint8Array(cert), { stream: false });
let infoArray = fdString.split('accountType');
@ -571,22 +588,26 @@ async function getConnectionStatus(exactly: boolean = true): Promise<boolean> {
function checkNetworkStatus(): Promise<void> {
return new Promise((resolve, reject) => {
let netHandle = connection.getDefaultNetSync();
connection.getNetCapabilities(netHandle, (error: BusinessError, data: connection.NetCapabilities) => {
if (error) {
HiLog.error(TAG, `checkNetworkStatus failed: ${JSON.stringify(error)}`);
try {
let netHandle = connection.getDefaultNetSync();
connection.getNetCapabilities(netHandle, (error: BusinessError, data: connection.NetCapabilities) => {
if (error) {
HiLog.error(TAG, `checkNetworkStatus failed: ${JSON.stringify(error)}`);
reject();
return;
}
HiLog.info(TAG, `network Succeeded to get data: ${JSON.stringify(data)}`);
const result = [connection.NetCap.NET_CAPABILITY_INTERNET, connection.NetCap.NET_CAPABILITY_VALIDATED]
.every(element => data.networkCap?.includes(element));
if (result) {
resolve();
return;
}
reject();
return;
};
HiLog.info(TAG, `network Succeeded to get data: ${JSON.stringify(data)}`);
const result = [connection.NetCap.NET_CAPABILITY_INTERNET, connection.NetCap.NET_CAPABILITY_VALIDATED]
.every(element => data.networkCap?.includes(element));
if (result) {
resolve();
return;
}
})
} catch (error) {
reject();
})
}
})
}

View File

@ -292,19 +292,27 @@ struct changeEncryption {
});
}
if (this.session !== undefined) {
this.session.terminateSelfWithResult({
'resultCode': 0,
'want': {
'bundleName': Constants.DLP_MANAGER_BUNDLE_NAME,
},
});
try {
this.session.terminateSelfWithResult({
'resultCode': 0,
'want': {
'bundleName': Constants.DLP_MANAGER_BUNDLE_NAME,
},
});
} catch (error) {
HiLog.error(TAG, `terminateSelfWithResult exception, error is ${JSON.stringify(error)}`);
}
} else {
if (GlobalContext.load('fileOpenHistoryFromMain')) {
(GlobalContext.load('fileOpenHistoryFromMain') as Map<string, Object>)
.delete(GlobalContext.load('uri') as string)
}
abilityResult.resultCode = 0;
(getContext(this) as common.UIAbilityContext).terminateSelfWithResult(abilityResult);
try {
(getContext(this) as common.UIAbilityContext).terminateSelfWithResult(abilityResult);
} catch (error) {
HiLog.error(TAG, `terminateSelfWithResult exception, error is ${JSON.stringify(error)}`);
}
}
}

View File

@ -115,11 +115,15 @@ struct encryptedSharing {
.onResult((data) => {
})
.onReceive((data) => {
let params: [] = JSON.parse((data.want as Want)?.parameters?.contactObjects as string);
for (let i = 0; i < params.length; i++) {
this.inputValue = (params[i] as Record<string, string>)?.telephone;
try {
let params: [] = JSON.parse((data.want as Want)?.parameters?.contactObjects as string);
for (let i = 0; i < params.length; i++) {
this.inputValue = (params[i] as Record<string, string>)?.telephone;
}
this.isShowSheet = false;
} catch (error) {
HiLog.error(TAG, `json parse exception, error is ${JSON.stringify(error)}`);
}
this.isShowSheet = false;
})
.width(Constants.CONTACTS_PICKER_WIDTH)
.height(Constants.CONTACTS_PICKER_HEIGHT)
@ -287,10 +291,14 @@ struct encryptedSharing {
generalFile[this.generalType] = arr;
this.actionWant.parameters['ability.picker.records'] = generalFile;
setTimeout(() => {
this.session!.terminateSelfWithResult({
resultCode: 2,
want: this.actionWant
});
try {
this.session!.terminateSelfWithResult({
resultCode: 2,
want: this.actionWant
});
} catch (error) {
HiLog.error(TAG, `terminateSelfWithResult exception, error is ${JSON.stringify(error)}`);
}
}, Constants.SHARE_SET_TIMEOUT)
}
}
@ -299,7 +307,13 @@ struct encryptedSharing {
if (!this.isInputInvalid) {
return false;
}
let credentialCallBack = JSON.parse(this.isInputInvalid) as Record<string, string>;
let credentialCallBack:Record<string, string> = {};
try {
credentialCallBack = JSON.parse(this.isInputInvalid) as Record<string, string>;
} catch (error) {
HiLog.error(TAG, `json parse exception, error is ${JSON.stringify(error)}`);
return false;
}
HiLog.info(TAG, `credential Call Back errorCode: ${credentialCallBack.errorCode}`);
if (!credentialCallBack.status && Number(credentialCallBack.errorCode) === Constants.ERR_CODE_SUCCESS) {
HiLog.info(TAG, `credentialCallBack msg`);
@ -515,9 +529,13 @@ struct encryptedSharing {
label: $r('app.string.ban'),
action: () => {
if (this.session !== undefined) {
this.session.terminateSelfWithResult({
'resultCode': 1,
});
try {
this.session.terminateSelfWithResult({
'resultCode': 1,
});
} catch (error) {
HiLog.error(TAG, `terminateSelfWithResult exception, error is ${JSON.stringify(error)}`);
}
}
}
}
@ -525,9 +543,13 @@ struct encryptedSharing {
isSaveIconRequired: false,
onCancel: () => {
if (this.session !== undefined) {
this.session.terminateSelfWithResult({
'resultCode': 0,
});
try {
this.session.terminateSelfWithResult({
'resultCode': 0,
});
} catch (error) {
HiLog.error(TAG, `terminateSelfWithResult exception, error is ${JSON.stringify(error)}`);
}
}
},
})

View File

@ -318,7 +318,11 @@ struct DlpDialog {
this.homeFeature.genDlpFileHome(filePathUri, GlobalContext.load('uri'), _dlp, async(err: number) => {
if (err !== 0) {
HiLog.error(TAG, `generateDLPFile failed: ${err}`);
fs.unlinkSync(filePath);
try {
fs.unlinkSync(filePath);
} catch (error) {
HiLog.error(TAG, `unlinkSync exception, error is ${JSON.stringify(error)}`);
}
let errorInfo =
{'title': '', 'msg': $r('app.string.MESSAGE_SERVICE_INSIDE_ERROR') } as Record<string, string | Resource>;
this.showErrorDialog(errorInfo.title, errorInfo.msg);
@ -331,7 +335,11 @@ struct DlpDialog {
}
});
}
fs.unlinkSync(filePath);
try {
fs.unlinkSync(filePath);
} catch (error) {
HiLog.error(TAG, `unlinkSync exception, error is ${JSON.stringify(error)}`);
}
await this.catchProcess();
this.processing = false;
GlobalContext.store('dlpFileName', this.srcFileName);
@ -535,8 +543,12 @@ struct DlpDialog {
async showData(defaultDlpProperty: dlpPermission.DLPProperty) {
let routerParams: Record<string, AuthAccount[]> = router.getParams() as Record<string, AuthAccount[]>;
this.permissionDict.forEach(async (item, index) => {
this.permissionDict[index].value =
$r(await getContext(this).resourceManager.getStringValue(item.value.id))
try {
this.permissionDict[index].value =
$r(await getContext(this).resourceManager.getStringValue(item.value.id));
} catch (error) {
HiLog.error(TAG, `getStringValue exception, error is ${JSON.stringify(error)}`);
}
})
let readOnlyData: dlpPermission.AuthUser[] =
defaultDlpProperty.authUserList?.filter((item: dlpPermission.AuthUser) => {

View File

@ -14,6 +14,7 @@
*/
import rpc from '@ohos.rpc';
import { HiLog } from '../../common/HiLog';
const TAG = 'dlpClass';
const ARRAY_LENGTH_MAX = 100;
@ -39,18 +40,28 @@ export class IAuthUser extends rpc.MessageSequence {
}
marshalling(dataOut: rpc.MessageSequence): boolean {
dataOut.writeString(this.authAccount);
dataOut.writeInt(this.authAccountType);
dataOut.writeInt(this.dlpFileAccess);
dataOut.writeLong(this.permExpiryTime);
try {
dataOut.writeString(this.authAccount);
dataOut.writeInt(this.authAccountType);
dataOut.writeInt(this.dlpFileAccess);
dataOut.writeLong(this.permExpiryTime);
} catch (error) {
HiLog.error(TAG, `marshalling exception, error is ${JSON.stringify(error)}`);
return false;
}
return true;
}
unmarshalling(dataIn: rpc.MessageSequence): boolean {
this.authAccount = dataIn.readString();
this.authAccountType = dataIn.readInt();
this.dlpFileAccess = dataIn.readInt();
this.permExpiryTime = dataIn.readLong();
try {
this.authAccount = dataIn.readString();
this.authAccountType = dataIn.readInt();
this.dlpFileAccess = dataIn.readInt();
this.permExpiryTime = dataIn.readLong();
} catch (error) {
HiLog.error(TAG, `unmarshalling exception, error is ${JSON.stringify(error)}`);
return false;
}
return true;
}
}
@ -87,34 +98,44 @@ export default class IDLDLPProperty extends rpc.MessageSequence {
}
marshalling(dataOut: rpc.MessageSequence): boolean {
dataOut.writeString(this.ownerAccount);
dataOut.writeString(this.ownerAccountID);
dataOut.writeInt(this.ownerAccountType);
dataOut.writeInt(this.authUserList.length);
dataOut.writeParcelableArray(this.authUserList);
dataOut.writeString(this.contactAccount);
dataOut.writeBoolean(this.offlineAccess);
dataOut.writeIntArray(this.everyoneAccessList);
dataOut.writeLong(this.expireTime);
try {
dataOut.writeString(this.ownerAccount);
dataOut.writeString(this.ownerAccountID);
dataOut.writeInt(this.ownerAccountType);
dataOut.writeInt(this.authUserList.length);
dataOut.writeParcelableArray(this.authUserList);
dataOut.writeString(this.contactAccount);
dataOut.writeBoolean(this.offlineAccess);
dataOut.writeIntArray(this.everyoneAccessList);
dataOut.writeLong(this.expireTime);
} catch (error) {
HiLog.error(TAG, `marshalling exception, error is ${JSON.stringify(error)}`);
return false;
}
return true;
}
unmarshalling(dataIn: rpc.MessageSequence): boolean {
this.ownerAccount = dataIn.readString();
this.ownerAccountID = dataIn.readString();
this.ownerAccountType = dataIn.readInt();
let arrayLength:number = dataIn.readInt();
if (arrayLength < ARRAY_LENGTH_MIN || arrayLength > ARRAY_LENGTH_MAX) {
try {
this.ownerAccount = dataIn.readString();
this.ownerAccountID = dataIn.readString();
this.ownerAccountType = dataIn.readInt();
let arrayLength:number = dataIn.readInt();
if (arrayLength < ARRAY_LENGTH_MIN || arrayLength > ARRAY_LENGTH_MAX) {
return false;
}
for (let i = 0; i < arrayLength; i++) {
this.authUserList.push(new IAuthUser('', 0, 0, 0));
}
dataIn.readParcelableArray(this.authUserList);
this.contactAccount = dataIn.readString();
this.offlineAccess = dataIn.readBoolean();
this.everyoneAccessList = dataIn.readIntArray();
this.expireTime = dataIn.readLong();
} catch (error) {
HiLog.error(TAG, `unmarshalling exception, error is ${JSON.stringify(error)}`);
return false;
}
for (let i = 0; i < arrayLength; i++) {
this.authUserList.push(new IAuthUser('', 0, 0, 0));
}
dataIn.readParcelableArray(this.authUserList);
this.contactAccount = dataIn.readString();
this.offlineAccess = dataIn.readBoolean();
this.everyoneAccessList = dataIn.readIntArray();
this.expireTime = dataIn.readLong();
return true;
}
}