harmony 鸿蒙ErrorObserver

  • 2025-06-12
  • 浏览 (4)

ErrorObserver

The ErrorObserver module defines an observer to listen for application errors. It can be used as an input parameter in ErrorManager.on to listen for errors that occur in the current application.

NOTE

The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

import { errorManager } from '@kit.AbilityKit';

ErrorObserver.onUnhandledException

onUnhandledException(errMsg: string): void

Called when an uncaught exception occurs in the application.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Ability.AbilityRuntime.Core

Parameters

Name Type Mandatory Description
errMsg string Yes Message and error stack trace about the exception.

Example

import { errorManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let observer: errorManager.ErrorObserver = {
  onUnhandledException(errorMsg) {
    console.error('onUnhandledException, errorMsg: ', errorMsg);
  }
};

try {
  errorManager.on('error', observer);
} catch (error) {
  console.error(`registerErrorObserver failed, error.code: ${(error as BusinessError).code}, error.message: ${(error as BusinessError).message}`);
}

ErrorObserver.onException10+

onException?(errObject: Error): void

Called when the application encounters an exception and reports it to the JavaScript layer.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Ability.AbilityRuntime.Core

Parameters

Name Type Mandatory Description
errObject Error Yes Event name, message, and error stack of the exception.

Example

import { errorManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let observer: errorManager.ErrorObserver = {
  onUnhandledException(errorMsg) {
    console.error('onUnhandledException, errorMsg: ', errorMsg);
  },
  onException(errorObj) {
    console.log('onException, name: ', errorObj.name);
    console.log('onException, message: ', errorObj.message);
    if (typeof (errorObj.stack) === 'string') {
      console.log('onException, stack: ', errorObj.stack);
    }
  }
};

try {
  errorManager.on('error', observer);
} catch (error) {
  console.error(`registerErrorObserver failed, error.code: ${(error as BusinessError).code}, error.message: ${(error as BusinessError).message}`);
}

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Ability Kit

harmony 鸿蒙AbilityAccessControl

harmony 鸿蒙AbilityBase

harmony 鸿蒙AbilityBase_Element

harmony 鸿蒙AbilityRuntime

harmony 鸿蒙bundle

harmony 鸿蒙OH_NativeBundle_ApplicationInfo

harmony 鸿蒙OH_NativeBundle_ElementName

harmony 鸿蒙ability_access_control.h

harmony 鸿蒙ability_base_common.h

0  赞