1# @ohos.app.ability.errorManager (ErrorManager)
2
3The ErrorManager module provides APIs for registering and unregistering error observers.
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```ts
11import { errorManager } from '@kit.AbilityKit';
12```
13
14## errorManager.on('error')
15
16> **NOTE**
17>
18> The **errormanager.on** API is registered only in the main thread. Currently, exceptions in child threads (such as TaskPool threads) cannot be captured.
19>
20> The application does not exit during the use of **errormanager.on**. You are advised to add the synchronous exit operation after the callback function is executed.
21
22on(type: 'error', observer: ErrorObserver): number
23
24Registers an error observer. After the registration, JS crashes generated by the application can be captured. When the application breaks down, the process does not exit.
25
26**Atomic service API**: This API can be used in atomic services since API version 11.
27
28**System capability**: SystemCapability.Ability.AbilityRuntime.Core
29
30**Parameters**
31
32| Name| Type| Mandatory| Description|
33| -------- | -------- | -------- | -------- |
34| type | string | Yes| Event type. It is fixed at **'error'**.|
35| observer | [ErrorObserver](js-apis-inner-application-errorObserver.md) | Yes| Digital code of the observer.|
36
37**Return value**
38
39  | Type| Description|
40  | -------- | -------- |
41  | number | Index of the observer.|
42
43**Error codes**
44
45For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
46
47| ID| Error Message|
48| ------- | -------- |
49| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
50| 16000003 | The specified ID does not exist. |
51
52**Example**
53
54```ts
55import { errorManager } from '@kit.AbilityKit';
56import { BusinessError } from '@kit.BasicServicesKit';
57
58let observer: errorManager.ErrorObserver = {
59  onUnhandledException(errorMsg) {
60    console.log('onUnhandledException, errorMsg: ', errorMsg);
61  },
62  onException(errorObj) {
63    console.log('onException, name: ', errorObj.name);
64    console.log('onException, message: ', errorObj.message);
65    if (typeof(errorObj.stack) === 'string') {
66      console.log('onException, stack: ', errorObj.stack);
67    }
68  }
69};
70let observerId = -1;
71
72try {
73  observerId = errorManager.on('error', observer);
74} catch (paramError) {
75  let code = (paramError as BusinessError).code;
76  let message = (paramError as BusinessError).message;
77  console.error(`error: ${code}, ${message}`);
78}
79```
80
81## errorManager.off('error')
82
83off(type: 'error', observerId: number,  callback: AsyncCallback\<void>): void
84
85Unregisters an error observer. This API uses an asynchronous callback to return the result.
86
87**Atomic service API**: This API can be used in atomic services since API version 11.
88
89**System capability**: SystemCapability.Ability.AbilityRuntime.Core
90
91**Parameters**
92
93| Name| Type| Mandatory| Description|
94| -------- | -------- | -------- | -------- |
95| type | string | Yes| Event type. It is fixed at **'error'**.|
96| observerId | number | Yes| Index of the observer returned by **on()**.|
97| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
98
99**Error codes**
100
101For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
102
103| ID| Error Message|
104| ------- | -------- |
105| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
106| 16000003 | The specified ID does not exist. |
107
108**Example**
109
110```ts
111import { errorManager } from '@kit.AbilityKit';
112import { BusinessError } from '@kit.BasicServicesKit';
113
114let observerId = 100;
115
116function unregisterErrorObserverCallback(err: BusinessError) {
117  if (err) {
118    console.error('------------ unregisterErrorObserverCallback ------------', err);
119  }
120}
121
122try {
123  errorManager.off('error', observerId, unregisterErrorObserverCallback);
124} catch (paramError) {
125  let code = (paramError as BusinessError).code;
126  let message = (paramError as BusinessError).message;
127  console.error(`error: ${code}, ${message}`);
128}
129```
130
131## errorManager.off('error')
132
133off(type: 'error', observerId: number): Promise\<void>
134
135Unregisters an error observer. This API uses a promise to return the result.
136
137**Atomic service API**: This API can be used in atomic services since API version 11.
138
139**System capability**: SystemCapability.Ability.AbilityRuntime.Core
140
141**Parameters**
142
143| Name| Type| Mandatory| Description|
144| -------- | -------- | -------- | -------- |
145| type | string | Yes| Event type. It is fixed at **'error'**.|
146| observerId | number | Yes| Index of the observer returned by **on()**.|
147
148**Return value**
149
150| Type| Description|
151| -------- | -------- |
152| Promise\<void> | Promise that returns no value.|
153
154**Error codes**
155
156For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
157
158| ID| Error Message|
159| ------- | -------- |
160| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
161| 16000003 | The specified ID does not exist. |
162
163**Example**
164
165```ts
166import { errorManager } from '@kit.AbilityKit';
167import { BusinessError } from '@kit.BasicServicesKit';
168
169let observerId = 100;
170
171try {
172  errorManager.off('error', observerId)
173    .then((data) => {
174      console.log('----------- unregisterErrorObserver success ----------', data);
175    })
176    .catch((err: BusinessError) => {
177      console.error('----------- unregisterErrorObserver fail ----------', err);
178    });
179} catch (paramError) {
180  let code = (paramError as BusinessError).code;
181  let message = (paramError as BusinessError).message;
182  console.error(`error: ${code}, ${message}`);
183}
184```
185
186## errorManager.on('loopObserver')<sup>12+</sup>
187
188on(type: 'loopObserver', timeout: number, observer: LoopObserver): void
189
190Registers an observer for the message processing duration of the main thread. After the registration, the execution time of a message processed by the main thread of the application can be captured.
191
192**Atomic service API**: This API can be used in atomic services since API version 12.
193
194**System capability**: SystemCapability.Ability.AbilityRuntime.Core
195
196**Parameters**
197
198| Name| Type| Mandatory| Description|
199| -------- | -------- | -------- | -------- |
200| type | string | Yes| Event type. It is fixed at **'loopObserver'**, indicating an observer for the message processing duration of the main thread.|
201| timeout | number | Yes|  Event execution threshold, in milliseconds. The value must be greater than **0**.|
202| observer | [LoopObserver](js-apis-inner-application-loopObserver.md) | Yes| Observer to register.|
203
204**Error codes**
205
206For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
207
208| ID| Error Message|
209| ------- | -------- |
210| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
211
212**Example**
213
214```ts
215import { errorManager } from '@kit.AbilityKit';
216
217let observer: errorManager.LoopObserver = {
218  onLoopTimeOut(timeout: number) {
219    console.log('Duration timeout: ' + timeout);
220  }
221};
222
223errorManager.on("loopObserver", 1, observer);
224```
225
226## errorManager.on('unhandledRejection')<sup>12+</sup>
227
228on(type: 'unhandledRejection', observer: UnhandledRejectionObserver): void
229
230Registers an observer for the promise rejection. After the registration, a rejected promise that is not captured in the current thread of the application can be captured.
231
232**Atomic service API**: This API can be used in atomic services since API version 12.
233
234**System capability**: SystemCapability.Ability.AbilityRuntime.Core
235
236**Parameters**
237
238| Name                  | Type                                                         | Mandatory| Description                                      |
239|-----------------------|-------------------------------------------------------------| -------- |------------------------------------------|
240| type                  | string                                                      | Yes| Event type. It is fixed at **'unhandledRejection'**, indicating an observer for the promise rejection.|
241| observer              | [UnhandledRejectionObserver](#unhandledrejectionobserver12) | Yes| Observer to register.                         |
242
243**Error codes**
244
245For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
246
247| ID| Error Message|
248| ------- | -------- |
249| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
250| 16200001 | If the caller is invalid. |
251
252**Example**
253
254```ts
255import { errorManager } from '@kit.AbilityKit';
256
257let observer: errorManager.UnhandledRejectionObserver = (reason: Error, promise: Promise<void>) => {
258  if (promise === promise1) {
259    console.log("promise1 is rejected");
260  }
261  console.log("reason.name: ", reason.name);
262  console.log("reason.message: ", reason.message);
263  if (reason.stack) {
264    console.log("reason.stack: ", reason.stack);
265  }
266};
267
268errorManager.on("unhandledRejection", observer);
269
270let promise1 = new Promise<void>(() => {}).then(() => {
271  throw new Error("uncaught error");
272});
273```
274
275## errorManager.off('loopObserver')<sup>12+</sup>
276
277off(type: 'loopObserver', observer?: LoopObserver): void
278
279Unregisters an observer for the message processing duration of the main thread.
280
281**Atomic service API**: This API can be used in atomic services since API version 12.
282
283**System capability**: SystemCapability.Ability.AbilityRuntime.Core
284
285**Parameters**
286
287| Name| Type| Mandatory| Description|
288| -------- | -------- | -------- | -------- |
289| type | string | Yes| Event type. It is fixed at **'loopObserver'**, indicating an observer for the message processing duration of the main thread.|
290| observer | [LoopObserver](js-apis-inner-application-loopObserver.md) | No| Observer to unregister.|
291
292**Error codes**
293
294For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
295
296| ID| Error Message|
297| ------- | -------- |
298| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
299
300**Example**
301
302```ts
303import { errorManager } from '@kit.AbilityKit';
304
305errorManager.off("loopObserver");
306```
307
308## errorManager.off('unhandledRejection')<sup>12+</sup>
309
310off(type: 'unhandledRejection', observer?: UnhandledRejectionObserver): void
311
312Unregisters an observer for the promise rejection.
313
314**Atomic service API**: This API can be used in atomic services since API version 12.
315
316**System capability**: SystemCapability.Ability.AbilityRuntime.Core
317
318**Parameters**
319
320| Name                  | Type                             | Mandatory| Description                                          |
321|-----------------------|---------------------------------|----|----------------------------------------------|
322| type                  | string                          | Yes | Event type. It is fixed at **'unhandledRejection'**, indicating an observer for the promise rejection.|
323| observer              | [UnhandledRejectionObserver](#unhandledrejectionobserver12) | No | Observer to unregister.                       |
324
325**Error codes**
326
327For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
328
329| ID| Error Message|
330| ------- | -------- |
331| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
332| 16200001 | If the caller is invalid. |
333| 16300004 | If the observer does not exist. |
334
335For details about the error codes, see [Ability Error Codes](errorcode-ability.md).
336
337**Example**
338
339```ts
340import { errorManager } from '@kit.AbilityKit';
341
342let observer: errorManager.UnhandledRejectionObserver = (reason: Error, promise: Promise<void>) => {
343  if (promise === promise1) {
344    console.log("promise1 is rejected");
345  }
346  console.log("reason.name: ", reason.name);
347  console.log("reason.message: ", reason.message);
348  if (reason.stack) {
349    console.log("reason.stack: ", reason.stack);
350  }
351};
352
353errorManager.on("unhandledRejection", observer);
354
355let promise1 = new Promise<void>(() => {}).then(() => {
356  throw new Error("uncaught error")
357})
358
359errorManager.off("unhandledRejection");
360```
361Or:
362```ts
363import { errorManager } from '@kit.AbilityKit';
364
365let observer: errorManager.UnhandledRejectionObserver = (reason: Error, promise: Promise<void>) => {
366  if (promise === promise1) {
367    console.log("promise1 is rejected");
368  }
369  console.log("reason.name: ", reason.name);
370  console.log("reason.message: ", reason.message);
371  if (reason.stack) {
372    console.log("reason.stack: ", reason.stack);
373  }
374};
375
376errorManager.on("unhandledRejection", observer);
377
378let promise1 = new Promise<void>(() => {}).then(() => {
379  throw new Error("uncaught error")
380})
381
382errorManager.off("unhandledRejection", observer);
383```
384
385## UnhandledRejectionObserver<sup>12+</sup>
386
387type UnhandledRejectionObserver = (reason: Error | any, promise: Promise\<any>) => void
388
389Defines an observer to capture the cause of a rejected promise.
390
391**Atomic service API**: This API can be used in atomic services since API version 12.
392
393**System capability**: SystemCapability.Ability.AbilityRuntime.Core
394
395**Parameters**
396
397| Name   | Type           | Mandatory| Description|
398|--------|---------------|---| -------- |
399| reason | Error \| any  | Yes| Generally, the value is of the **Error** type, indicating the reason for rejection.|
400| promise | Promise\<any> | Yes| Rejected promise.|
401