代码均由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可收集某一类异常出现概率

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐