• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# ErrorObserver
2
3The **ErrorObserver** module defines an observer to listen for application errors. It can be used as an input parameter in [ErrorManager.on](js-apis-app-ability-errorManager.md#errormanageron) to listen for errors that occur in the current application.
4
5> **NOTE**
6>
7> 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.
8
9## Modules to Import
10
11```ts
12import errorManager from '@ohos.app.ability.errorManager';
13```
14
15## ErrorObserver.onUnhandledException
16
17onUnhandledException(errMsg: string): void;
18
19Called when an unhandled exception occurs in the JS runtime.
20
21**System capability**: SystemCapability.Ability.AbilityRuntime.Core
22
23**Parameters**
24
25| Name| Type| Mandatory| Description|
26| -------- | -------- | -------- | -------- |
27| errMsg | string | Yes| Message and error stack trace about the exception.|
28
29**Example**
30
31```ts
32import errorManager from '@ohos.app.ability.errorManager';
33
34let observer: errorManager.ErrorObserver = {
35  onUnhandledException(errorMsg) {
36    console.error('onUnhandledException, errorMsg: ', errorMsg);
37  }
38};
39
40try {
41    errorManager.on('error', observer);
42} catch (error) {
43    console.error('registerErrorObserver failed, error.code: ${error.code}, error.message: ${error.message}');
44}
45```
46
47## ErrorObserver.onException<sup>10+</sup>
48
49onException?(errObject: Error): void;
50
51Called when an exception occurs during the application running.
52
53**System capability**: SystemCapability.Ability.AbilityRuntime.Core
54
55**Parameters**
56
57| Name| Type| Mandatory| Description|
58| -------- | -------- | -------- | -------- |
59| errObject | Error | Yes| Event name, message, and error stack of the exception.|
60
61**Example**
62
63```ts
64import errorManager from '@ohos.app.ability.errorManager';
65
66let observer: errorManager.ErrorObserver = {
67  onUnhandledException(errorMsg) {
68    console.error('onUnhandledException, errorMsg: ', errorMsg);
69  },
70  onException(errorObj) {
71    console.log('onException, name: ', errorObj.name);
72    console.log('onException, message: ', errorObj.message);
73    if (typeof(errorObj.stack) === 'string') {
74        console.log('onException, stack: ', errorObj.stack);
75    }
76  }
77};
78
79try {
80    errorManager.on('error', observer);
81} catch (error) {
82    console.error('registerErrorObserver failed, error.code: ${error.code}, error.message: ${error.message}');
83}
84```
85