HarmonyOS ArkTS是否有类似ts的捕获Promise中未处理的异常api吗,类似:unhandledrejection

HarmonyOS
2天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu
window.addEventListener('unhandledrejection', function(event) {
  // 这个事件对象有两个特殊的属性:
  alert(event.promise); // [object Promise] —— 生成该全局 error 的 promise
  alert(event.reason); // Error: Whoops! —— 未处理的 error 对象
});

已实现捕获promise异常:

import errorManager from '@ohos.app.ability.errorManager';
import { BusinessError } from '@ohos.base';
@Entry
@Component
struct Page422 {
  @State message: string = 'Hello World';
  aboutToAppear(): void {
    console.log("aaaaa-1")
    let promise1 = new Promise<boolean>((resolve, reject) => {
      resolve(true)
      reject(new Error('[uncaught error]Let it reject!!!'));
    }).then(() => {
      console.log("aaaaa-3")
    })
    let observer: errorManager.UnhandledRejectionObserver = (reason: Error, promise: Promise<void>) => {
      console.log("aaaaa-4")
      if (promise === promise1) {
        console.log("promise1 is rejected");
      }
      console.log("reason.name: ", reason.name);
      console.log("reason.message: ", reason.message);
      if (reason.stack) {
        console.log("reason.stack: ", reason.stack);
      }
    };
    try {
      errorManager.on('error', observer);
      errorManager.on('unhandledRejection', observer);
    } catch (paramError) {
      let code = (paramError as BusinessError).code;
      let message = (paramError as BusinessError).message;
      console.error(`error: ${code}, ${message}`);
    }
  }
  build() {
    RelativeContainer() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(() => {
          let a = new Promise<boolean>((_, reject) => {
            reject(new Error('[uncaught error]Let it reject!!!'));
          })
          a
        })
    }.height('100%').width('100%')
  }
}
分享
微博
QQ
微信
回复
2天前
相关问题
是否类似fastjson库?
260浏览 • 1回复 待解决
HarmonyOS 类似bugly开发包
17浏览 • 1回复 待解决