1# @ohos.app.ability.errorManager (ErrorManager)
2
3ErrorManager模块提供对错误观察器的注册和注销的能力。
4
5> **说明:**
6>
7> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8
9## 导入模块
10```ts
11import { errorManager } from '@kit.AbilityKit';
12```
13
14## errorManager.on('error')
15
16> **注意:**
17>
18> 在主线程注册errormanager.on接口,当前版本不支持捕获子线程(如:taskpool)中的异常。
19>
20> 使用errormanager.on接口应用不会退出,建议在回调函数执行完后,增加同步退出操作。
21
22on(type: 'error', observer: ErrorObserver): number
23
24注册错误观测器。注册后可以捕获到应用产生的js crash,应用崩溃时进程不会退出。
25
26**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
27
28**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
29
30**参数:**
31
32| 参数名 | 类型 | 必填 | 说明 |
33| -------- | -------- | -------- | -------- |
34| type | string | 是 | 填写'error',表示错误观察器。 |
35| observer | [ErrorObserver](js-apis-inner-application-errorObserver.md) | 是 | 错误观察器。 |
36
37**返回值:**
38
39  | 类型 | 说明 |
40  | -------- | -------- |
41  | number | 观察器的index值,和观察器一一对应。 |
42
43**错误码**:
44
45以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
46
47| 错误码ID | 错误信息 |
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**示例:**
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
85注销错误观测器。使用callback异步返回。
86
87**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
88
89**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
90
91**参数:**
92
93| 参数名 | 类型 | 必填 | 说明 |
94| -------- | -------- | -------- | -------- |
95| type | string | 是 | 填写'error',表示错误观察器。 |
96| observerId | number | 是 | 由on方法返回的观察器的index值。 |
97| callback | AsyncCallback\<void> | 是 | 表示指定的回调方法。 |
98
99**错误码**:
100
101以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
102
103| 错误码ID | 错误信息 |
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**示例:**
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
135注销错误观测器。使用Promise异步返回。
136
137**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
138
139**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
140
141**参数:**
142
143| 参数名 | 类型 | 必填 | 说明 |
144| -------- | -------- | -------- | -------- |
145| type | string | 是 | 填写'error',表示错误观察器。 |
146| observerId | number | 是 | 由on方法返回的观察器的index值。 |
147
148**返回值:**
149
150| 类型 | 说明 |
151| -------- | -------- |
152| Promise\<void> | Promise对象。无返回结果的Promise对象。 |
153
154**错误码**:
155
156以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
157
158| 错误码ID | 错误信息 |
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**示例:**
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
190注册主线程消息处理耗时监听器。注册后可以捕获到应用主线程处理消息的具体执行时间。
191
192**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
193
194**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
195
196**参数:**
197
198| 参数名 | 类型 | 必填 | 说明 |
199| -------- | -------- | -------- | -------- |
200| type | string | 是 | 填写'loopObserver',表示注册主线程消息处理耗时监听器。 |
201| timeout | number | 是 |  表示事件执行阈值(单位:毫秒)。 阈值必须大于0。 |
202| observer | [LoopObserver](js-apis-inner-application-loopObserver.md) | 是 | 注册主线程消息处理耗时监听器。 |
203
204**错误码**:
205
206以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
207
208| 错误码ID | 错误信息 |
209| ------- | -------- |
210| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
211
212**示例:**
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
230注册被拒绝promise监听器。注册后可以捕获到当前线程中未被捕获到的promise rejection。
231
232**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
233
234**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
235
236**参数:**
237
238| 参数名                   | 类型                                                          | 必填 | 说明                                       |
239|-----------------------|-------------------------------------------------------------| -------- |------------------------------------------|
240| type                  | string                                                      | 是 | 填写'unhandledRejection',表示注册被拒绝promise监听器。 |
241| observer              | [UnhandledRejectionObserver](#unhandledrejectionobserver12) | 是 | 注册被拒绝promise监听器。                          |
242
243**错误码**:
244
245以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
246
247| 错误码ID | 错误信息 |
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**示例:**
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
279注销主线程消息处理监听器。
280
281**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
282
283**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
284
285**参数:**
286
287| 参数名 | 类型 | 必填 | 说明 |
288| -------- | -------- | -------- | -------- |
289| type | string | 是 | 填写'loopObserver',表示应用主线程观察器。 |
290| observer | [LoopObserver](js-apis-inner-application-loopObserver.md) | 否 | 应用主线程观察器标志。 |
291
292**错误码**:
293
294以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
295
296| 错误码ID | 错误信息 |
297| ------- | -------- |
298| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
299
300**示例:**
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
312注销被拒绝promise监听器。
313
314**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
315
316**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
317
318**参数:**
319
320| 参数名                   | 类型                              | 必填 | 说明                                           |
321|-----------------------|---------------------------------|----|----------------------------------------------|
322| type                  | string                          | 是  | 填写'unhandledRejection',表示注册被拒绝promise监听器。 |
323| observer              | [UnhandledRejectionObserver](#unhandledrejectionobserver12) | 否  | 注册了被拒绝promise监听器。                        |
324
325**错误码**:
326
327以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
328
329| 错误码ID | 错误信息 |
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
335以上错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。
336
337**示例:**
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```
361或者
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## ErrorObserver
386
387type ErrorObserver = _ErrorObserver.default
388
389ErrorObserver模块。
390
391**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
392
393**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
394
395| 类型 | 说明 |
396| --- | --- |
397| [_ErrorObserver.default](js-apis-inner-application-errorObserver.md) | ErrorObserver模块。 |
398
399## LoopObserver<sup>12+</sup>
400
401type LoopObserver = _LoopObserver
402
403LoopObserver模块。
404
405**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
406
407**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
408
409| 类型 | 说明 |
410| --- | --- |
411| [_LoopObserver](js-apis-inner-application-loopObserver.md) | LoopObserver模块。 |
412
413## UnhandledRejectionObserver<sup>12+</sup>
414
415type UnhandledRejectionObserver = (reason: Error | any, promise: Promise\<any>) => void
416
417定义异常监听,用于捕获Promise异步操作失败的原因。
418
419**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
420
421**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
422
423**参数:**
424
425| 参数名    | 类型            | 必填 | 说明 |
426|--------|---------------|---| -------- |
427| reason | Error \| any  | 是 | 通常是`Error`类型,表示被拒绝的理由。 |
428| promise | Promise\<any> | 是 | 被拒绝的promise。 |
429