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
16on(type: 'error', observer: ErrorObserver): number
17
18注册错误观测器。注册后可以捕获到应用产生的js crash,应用崩溃时进程不会退出。
19
20**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
21
22**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
23
24**参数:**
25 
26| 参数名 | 类型 | 必填 | 说明 |
27| -------- | -------- | -------- | -------- |
28| type | string | 是 | 填写'error',表示错误观察器。 |
29| observer | [ErrorObserver](js-apis-inner-application-errorObserver.md) | 是 | 错误观察器。 |
30
31**返回值:**
32
33  | 类型 | 说明 |
34  | -------- | -------- |
35  | number | 观察器的index值,和观察器一一对应。 |
36
37**错误码**:
38
39以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
40
41| 错误码ID | 错误信息 |
42| ------- | -------- |
43| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
44| 16000003 | The specified ID does not exist. |
45
46**示例:**
47    
48```ts
49import { errorManager } from '@kit.AbilityKit';
50import { BusinessError } from '@kit.BasicServicesKit';
51
52let observer: errorManager.ErrorObserver = {
53  onUnhandledException(errorMsg) {
54    console.log('onUnhandledException, errorMsg: ', errorMsg);
55  },
56  onException(errorObj) {
57    console.log('onException, name: ', errorObj.name);
58    console.log('onException, message: ', errorObj.message);
59    if (typeof(errorObj.stack) === 'string') {
60      console.log('onException, stack: ', errorObj.stack);
61    }
62  }
63};
64let observerId = -1;
65
66try {
67  observerId = errorManager.on('error', observer);
68} catch (paramError) {
69  let code = (paramError as BusinessError).code;
70  let message = (paramError as BusinessError).message;
71  console.error(`error: ${code}, ${message}`);
72}
73```
74
75## errorManager.off('error')
76
77off(type: 'error', observerId: number,  callback: AsyncCallback\<void>): void
78
79注销错误观测器。使用callback异步返回。
80
81**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
82
83**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
84
85**参数:**
86 
87| 参数名 | 类型 | 必填 | 说明 |
88| -------- | -------- | -------- | -------- |
89| type | string | 是 | 填写'error',表示错误观察器。 |
90| observerId | number | 是 | 由on方法返回的观察器的index值。 |
91| callback | AsyncCallback\<void> | 是 | 表示指定的回调方法。 |
92
93**错误码**:
94
95以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
96
97| 错误码ID | 错误信息 |
98| ------- | -------- |
99| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
100| 16000003 | The specified ID does not exist. |
101
102**示例:**
103    
104```ts
105import { errorManager } from '@kit.AbilityKit';
106import { BusinessError } from '@kit.BasicServicesKit';
107
108let observerId = 100;
109
110function unregisterErrorObserverCallback(err: BusinessError) {
111  if (err) {
112    console.error('------------ unregisterErrorObserverCallback ------------', err);
113  }
114}
115
116try {
117  errorManager.off('error', observerId, unregisterErrorObserverCallback);
118} catch (paramError) {
119  let code = (paramError as BusinessError).code;
120  let message = (paramError as BusinessError).message;
121  console.error(`error: ${code}, ${message}`);
122}
123```
124
125## errorManager.off('error')
126
127off(type: 'error', observerId: number): Promise\<void>
128
129注销错误观测器。使用Promise异步返回。
130
131**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
132
133**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
134
135**参数:**
136 
137| 参数名 | 类型 | 必填 | 说明 |
138| -------- | -------- | -------- | -------- |
139| type | string | 是 | 填写'error',表示错误观察器。 |
140| observerId | number | 是 | 由on方法返回的观察器的index值。 |
141
142**返回值:**
143
144| 类型 | 说明 |
145| -------- | -------- |
146| Promise\<void> | Promise对象。无返回结果的Promise对象。 |
147
148**错误码**:
149
150以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
151
152| 错误码ID | 错误信息 |
153| ------- | -------- |
154| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
155| 16000003 | The specified ID does not exist. |
156
157**示例:**
158    
159```ts
160import { errorManager } from '@kit.AbilityKit';
161import { BusinessError } from '@kit.BasicServicesKit';
162
163let observerId = 100;
164
165try {
166  errorManager.off('error', observerId)
167    .then((data) => {
168      console.log('----------- unregisterErrorObserver success ----------', data);
169    })
170    .catch((err: BusinessError) => {
171      console.error('----------- unregisterErrorObserver fail ----------', err);
172    });
173} catch (paramError) {
174  let code = (paramError as BusinessError).code;
175  let message = (paramError as BusinessError).message;
176  console.error(`error: ${code}, ${message}`);
177}
178```
179
180## errorManager.on('loopObserver')<sup>12+</sup>
181
182on(type: 'loopObserver', timeout: number, observer: LoopObserver): void
183
184注册主线程消息处理耗时监听器。注册后可以捕获到应用主线程处理消息的具体执行时间。
185
186**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
187
188**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
189
190**参数:**
191 
192| 参数名 | 类型 | 必填 | 说明 |
193| -------- | -------- | -------- | -------- |
194| type | string | 是 | 填写'loopObserver',表示注册主线程消息处理耗时监听器。 |
195| timeout | number | 是 |  表示事件执行阈值(单位:毫秒)。 阈值必须大于0。 |
196| observer | [LoopObserver](js-apis-inner-application-loopObserver.md) | 是 | 注册主线程消息处理耗时监听器。 |
197
198**错误码**:
199
200以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
201
202| 错误码ID | 错误信息 |
203| ------- | -------- |
204| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
205
206**示例:**
207    
208```ts
209import { errorManager } from '@kit.AbilityKit';
210
211let observer: errorManager.LoopObserver = {
212  onLoopTimeOut(timeout: number) {
213    console.log('Duration timeout: ' + timeout);
214  }
215};
216
217errorManager.on("loopObserver", 1, observer);
218```
219
220## errorManager.on('unhandledRejection')<sup>12+</sup>
221
222on(type: 'unhandledRejection', observer: UnhandledRejectionObserver): void
223
224注册被拒绝promise监听器。注册后可以捕获到当前线程中未被捕获到的promise rejection。
225
226**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
227
228**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
229
230**参数:**
231 
232| 参数名                   | 类型                                                          | 必填 | 说明                                       |
233|-----------------------|-------------------------------------------------------------| -------- |------------------------------------------|
234| type                  | string                                                      | 是 | 填写'unhandledRejection',表示注册被拒绝promise监听器。 |
235| observer              | [UnhandledRejectionObserver](#unhandledrejectionobserver12) | 是 | 注册被拒绝promise监听器。                          |
236
237**错误码**:
238
239以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
240
241| 错误码ID | 错误信息 |
242| ------- | -------- |
243| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
244| 16200001 | If the caller is invalid. |
245
246**示例:**
247    
248```ts
249import { errorManager } from '@kit.AbilityKit';
250
251let observer: errorManager.UnhandledRejectionObserver = (reason: Error, promise: Promise<void>) => {
252  if (promise === promise1) {
253    console.log("promise1 is rejected");
254  }
255  console.log("reason.name: ", reason.name);
256  console.log("reason.message: ", reason.message);
257  if (reason.stack) {
258    console.log("reason.stack: ", reason.stack);
259  }
260};
261
262errorManager.on("unhandledRejection", observer);
263
264let promise1 = new Promise<void>(() => {}).then(() => {
265  throw new Error("uncaught error");
266});
267```
268
269## errorManager.off('loopObserver')<sup>12+</sup>
270
271off(type: 'loopObserver', observer?: LoopObserver): void
272
273注销主线程消息处理监听器。
274
275**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
276
277**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
278
279**参数:**
280 
281| 参数名 | 类型 | 必填 | 说明 |
282| -------- | -------- | -------- | -------- |
283| type | string | 是 | 填写'loopObserver',表示应用主线程观察器。 |
284| observer | [LoopObserver](js-apis-inner-application-loopObserver.md) | 否 | 应用主线程观察器标志。 |
285
286**错误码**:
287
288以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
289
290| 错误码ID | 错误信息 |
291| ------- | -------- |
292| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
293
294**示例:**
295    
296```ts
297import { errorManager } from '@kit.AbilityKit';
298
299errorManager.off("loopObserver");
300```
301
302## errorManager.off('unhandledRejection')<sup>12+</sup>
303
304off(type: 'unhandledRejection', observer?: UnhandledRejectionObserver): void
305
306注销被拒绝promise监听器。
307
308**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
309
310**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
311
312**参数:**
313
314| 参数名                   | 类型                              | 必填 | 说明                                           |
315|-----------------------|---------------------------------|----|----------------------------------------------|
316| type                  | string                          | 是  | 填写'unhandledRejection',表示注册被拒绝promise监听器。 |
317| observer              | [UnhandledRejectionObserver](#unhandledrejectionobserver12) | 否  | 注册了被拒绝promise监听器。                        |
318
319**错误码**:
320
321以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)和[元能力子系统错误码](errorcode-ability.md)。
322
323| 错误码ID | 错误信息 |
324| ------- | -------- |
325| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed.   |
326| 16200001 | If the caller is invalid. |
327| 16300004 | If the observer does not exist. |
328
329以上错误码详细介绍请参考[元能力子系统错误码](errorcode-ability.md)。
330
331**示例:**
332    
333```ts
334import { errorManager } from '@kit.AbilityKit';
335
336let observer: errorManager.UnhandledRejectionObserver = (reason: Error, promise: Promise<void>) => {
337  if (promise === promise1) {
338    console.log("promise1 is rejected");
339  }
340  console.log("reason.name: ", reason.name);
341  console.log("reason.message: ", reason.message);
342  if (reason.stack) {
343    console.log("reason.stack: ", reason.stack);
344  }
345};
346
347errorManager.on("unhandledRejection", observer);
348
349let promise1 = new Promise<void>(() => {}).then(() => {
350  throw new Error("uncaught error")
351})
352
353errorManager.off("unhandledRejection");
354```
355或者
356```ts
357import { errorManager } from '@kit.AbilityKit';
358
359let observer: errorManager.UnhandledRejectionObserver = (reason: Error, promise: Promise<void>) => {
360  if (promise === promise1) {
361    console.log("promise1 is rejected");
362  }
363  console.log("reason.name: ", reason.name);
364  console.log("reason.message: ", reason.message);
365  if (reason.stack) {
366    console.log("reason.stack: ", reason.stack);
367  }
368};
369
370errorManager.on("unhandledRejection", observer);
371
372let promise1 = new Promise<void>(() => {}).then(() => {
373  throw new Error("uncaught error")
374})
375
376errorManager.off("unhandledRejection", observer);
377```
378
379## UnhandledRejectionObserver<sup>12+</sup>
380
381type UnhandledRejectionObserver = (reason: Error | any, promise: Promise\<any>) => void
382
383定义异常监听,用于捕获Promise异步操作失败的原因。
384
385**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
386
387**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
388
389**参数:**
390
391| 参数名    | 类型            | 必填 | 说明 |
392|--------|---------------|---| -------- |
393| reason | Error \| any  | 是 | 通常是`Error`类型,表示被拒绝的理由。 |
394| promise | Promise\<any> | 是 | 被拒绝的promise。 |
395