ArkTS TypeScript 实现前置通知、后置通知、环绕通知、异常通知
可以使用环绕通知实现记录一个方法的耗时,异常通知用于改善程序中过多的try catch 冗余代码,或者是针对出现的异常做一个集中的异常处理handler可收集某一类异常出现概率。代码均由chatgpt生成。
·
代码均由chatgpt生成
// 前置通知
export function Before(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Before calling ${propertyKey} with arguments: ${JSON.stringify(args)}`);
return originalMethod.apply(this, args);
};
}
// 后置通知
export function After(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
const result = originalMethod.apply(this, args);
console.log(`After calling ${propertyKey}, result: ${result}`);
return result;
};
}
// 环绕通知
export function Around(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Around: Before calling ${propertyKey} with arguments: ${JSON.stringify(args)}`);
const result = originalMethod.apply(this, args);
console.log(`Around: After calling ${propertyKey}, result: ${result}`);
return result;
};
}
// 异常通知 出现异常返回指定的返回值
export function Exception<T>(defaultReturnValue?: T) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]): T {
try {
return originalMethod.apply(this, args);
} catch (error) {
console.error(`Exception in method ${propertyKey}: ${error.message}`); // 打印异常信息
return defaultReturnValue;
}
};
};
}
// 异常通知 支持异步方法
export function AsyncException<T>(defaultReturnValue?: T) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]): Promise<T> {
try {
return await originalMethod.apply(this, args);
} catch (error) {
console.error(`Exception in async method ${propertyKey}: ${error.message}`);
return Promise.resolve(defaultReturnValue);
}
};
};
}
使用方式
Exception()
func_01() {
if (true) {
throw new Error("tomas 自定义异常");
}
}
Exception(2)
func_02(): number {
if (true) {
throw new Error("tomas 自定义异常2");
}
return 1;
}
this.func_01();
LogUtil.info('func_02 出现异常执行结果' + this.func_02());
// out
Exception in method func_01: tomas 自定义异常
Exception in method func_02: tomas 自定义异常2
func_02 出现异常执行结果2
可以使用环绕通知实现记录一个方法的耗时,异常通知用于改善程序中过多的try catch 冗余代码,或者是针对出现的异常做一个集中的异常处理handler可收集某一类异常出现概率
更多推荐



所有评论(0)