• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Error Handling Using JSVM-API
2
3## Introduction
4
5JSVM-API provides APIs for handling errors occurred in JavaScript (JS) code using exceptions. Properly using these APIs helps improve module stability and reliability.
6
7## Basic Concepts
8
9Exceptions and errors are common concepts in JS programming. An exception indicates the presence of an unexpected condition, and an error indicates that the application cannot perform certain operations correctly. JSVM-API provides a set of APIs for handling errors occurred in JS code using exceptions. Read on the following to learn basic concepts related to exception handling:
10
11- Exception: indicates an unexpected condition that may occur during the execution of an application. It can be a syntax error, runtime error, or logic error. For example, the division of a non-zero value with zero and an operation on undefined variables are exceptions.
12- Error: indicates that the application cannot perform some operations. Errors can be defined by the underlying system, API, or developer.
13- **TypeError**: indicates that the type of an operation or value does not meet the expectation. Generally, this error is caused by an incorrect data type.
14- **RangeError**: indicates that a value is not in the expected range. For example, an index beyond the array length is accessed.
15- **SyntaxError**: indicates a mistake in the syntax of a piece of code.
16
17These concepts are important in exception and error handling. Properly using methods to capture, handle, or report exceptions and errors help improve application stability. JSVM-API provides APIs for handling errors in JS code using exceptions.
18
19## Available APIs
20
21| API                      | Description                      |
22|----------------------------|--------------------------------|
23| OH_JSVM_CreateError, OH_JSVM_CreateTypeError, OH_JSVM_CreateRangeError, OH_JSVM_CreateSyntaxError | Creates a JS error. The created error object can be thrown to ArkTS using **napi_throw**. |
24| OH_JSVM_Throw | Throws a JS error object, which is created by **OH_JSVM_CreateError** or obtained by **OH_JSVM_GetLastErrorInfo**. |
25| OH_JSVM_ThrowError, OH_JSVM_ThrowTypeError, OH_JSVM_ThrowRangeError, OH_JSVM_ThrowSyntaxError | Throws a JS error object. |
26| OH_JSVM_IsError              | Checks whether the given **JSVM_Value** indicates an error.|
27| OH_JSVM_GetAndClearLastException    | Obtains and clears the last JS exception.|
28| OH_JSVM_IsExceptionPending   | Checks whether there is any pending exception.|
29
30## Example
31
32If you are just starting out with JSVM-API, see [JSVM-API Development Process](use-jsvm-process.md). The following demonstrates only the C++ and ArkTS code related to exception handling.
33
34### OH_JSVM_Throw
35
36Use **OH_JSVM_Throw** to throw a JS error object so that the error can be captured and handled.
37
38### OH_JSVM_CreateError
39
40Creates a JS error object with text information.
41
42CPP code:
43
44```cpp
45// hello.cpp
46#include "napi/native_api.h"
47#include "ark_runtime/jsvm.h"
48// Register the JsVmCreateThrowError callback.
49static JSVM_CallbackStruct param[] = {
50    {.data = nullptr, .callback = JsVmCreateThrowError},
51};
52static JSVM_CallbackStruct *method = param;
53// Set a property descriptor named jsVmCreateThrowError and associate it with a callback. This allows the JsVmCreateThrowError callback to be called from JS.
54static JSVM_PropertyDescriptor descriptor[] = {
55    {"jsVmCreateThrowError", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
56};
57static JSVM_Value JsVmCreateThrowError(JSVM_Env env, JSVM_CallbackInfo info) {
58{
59    size_t argc = 1;
60    JSVM_Value argv[1] = {nullptr};
61    OH_JSVM_GetCbInfo(env, info, &argc, argv, nullptr, nullptr);
62    // Create a string in the JSVM and store it in the errorCode variable.
63    JSVM_Value errorCode = nullptr;
64    OH_JSVM_CreateStringUtf8(env, "-1", JSVM_AUTO_LENGTH, &errorCode);
65    // Create a string in the JSVM and store it in the errorMessage variable.
66    JSVM_Value errorMessage = nullptr;
67    OH_JSVM_CreateStringUtf8(env, "HasError", JSVM_AUTO_LENGTH, &errorMessage);
68    // Create a JS error object.
69    JSVM_Value error = nullptr;
70    OH_JSVM_CreateError(env, errorCode, errorMessage, &error);
71    // Call OH_JSVM_Throw to throw the error.
72    OH_JSVM_Throw(env, error);
73    return nullptr;
74}
75```
76
77
78
79ArkTS code:
80
81```ts
82import hilog from "@ohos.hilog"
83// Import the native APIs.
84import napitest from "libentry.so"
85let script: string = `
86   jsVmCreateThrowError();
87`
88try {
89  testNapi.runJsVm(script);
90} catch (error) {
91  hilog.error(0x0000, 'testTag', 'Test OH_JSVM_Throw errorCode: %{public}s, errorMessage: %{public}s', error.code, error.message);
92}
93```
94
95### OH_JSVM_ThrowError
96
97Use **OH_JSVM_ThrowError** to throw a JS **Error** object with text information.
98
99CPP code:
100
101```cpp
102// hello.cpp
103#include "napi/native_api.h"
104#include "ark_runtime/jsvm.h"
105// Register the JsVmThrowError callback.
106static JSVM_CallbackStruct param[] = {
107    {.data = nullptr, .callback = JsVmThrowError},
108};
109static JSVM_CallbackStruct *method = param;
110// Set a property descriptor named jsVmThrowError and associate it with a callback. This allows the JsVmThrowError callback to be called from JS.
111static JSVM_PropertyDescriptor descriptor[] = {
112    {"jsVmThrowError", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
113};
114static JSVM_Value JsVmThrowError(JSVM_Env env, JSVM_CallbackInfo info)
115{
116    size_t argc = 1;
117    JSVM_Value argv[1] = {nullptr};
118    OH_JSVM_GetCbInfo(env, info, &argc, argv, nullptr, nullptr);
119    if (argc == 0) {
120        // Throw an exception if no parameter is passed in.
121        OH_JSVM_ThrowError(env, "-1", "has Error");
122    } else if (argc == 1) {
123        size_t length;
124        // Obtain the length of the string passed from JS from the input parameter.
125        OH_JSVM_GetValueStringUtf8(env, argv[0], nullptr, 0, &length);
126        char *buffer = new char[length + 1];
127        // Obtain the string of the input parameter.
128        OH_JSVM_GetValueStringUtf8(env, argv[0], buffer, length + 1, nullptr);
129        // Populate the error information to OH_JSVM_ThrowError.
130        OH_JSVM_ThrowError(env, nullptr, buffer);
131        delete[] buffer;
132    }
133    return nullptr;
134}
135```
136
137ArkTS code:
138
139```ts
140import hilog from "@ohos.hilog"
141// Import the native APIs.
142import napitest from "libentry.so"
143let firstScript: string = `jsVmThrowError()`
144try {
145    napitest.runJsVm(firstScript);
146} catch (error) {
147    hilog.error(0x0000, 'testTag', 'Test OH_JSVM_ThrowError errorCode: %{public}s, errorMessage: %{public}s', error.code, error.message);
148}
149
150try {
151    let errMessage = `\"has Error\"`
152    let sencodeScript: string =
153        `
154            jsVmThrowError(${errMessage})
155        `
156    napitest.runJsVm(sencodeScript);
157} catch (error) {
158  hilog.error(0x0000, 'testTag', 'Test OH_JSVM_ThrowError errorCode: %{public}s, errorMessage: %{public}s', error.code, error.message);
159}
160```
161
162### OH_JSVM_ThrowTypeError
163
164Use **OH_JSVM_ThrowTypeError** to throw a JS **TypeError** object with text information.
165
166CPP code:
167
168```cpp
169// hello.cpp
170#include "napi/native_api.h"
171#include "ark_runtime/jsvm.h"
172// Register the **JsVmThrowTypeError** callback.
173static JSVM_CallbackStruct param[] = {
174    {.data = nullptr, .callback = JsVmThrowTypeError},
175};
176static JSVM_CallbackStruct *method = param;
177// Set a property descriptor named jsVmThrowTypeError and associate it with a callback. This allows the JsVmThrowTypeError callback to be called from JS.
178static JSVM_PropertyDescriptor descriptor[] = {
179    {"jsVmThrowTypeError", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
180};
181// Throw a type error with an error message.
182static JSVM_Value JsVmThrowTypeError(JSVM_Env env, JSVM_CallbackInfo info)
183{
184    size_t argc = 1;
185    JSVM_Value argv[1] = {nullptr};
186    OH_JSVM_GetCbInfo(env, info, &argc, argv, nullptr, nullptr);
187    if (argc == 0) {
188        // Throw an error if no parameter is passed in.
189        OH_JSVM_ThrowTypeError(env, "-1", "throwing type error");
190    } else if (argc == 1) {
191        size_t length;
192        // Obtain the length of the string in the input parameter passed from JS.
193        OH_JSVM_GetValueStringUtf8(env, argv[0], nullptr, 0, &length);
194        char *buffer = new char[length + 1];
195        // Obtain the string of the input parameter.
196        OH_JSVM_GetValueStringUtf8(env, argv[0], buffer, length + 1, nullptr);
197        // Populate the error information to OH_JSVM_ThrowError.
198        OH_JSVM_ThrowTypeError(env, nullptr, buffer);
199        delete[] buffer;
200    }
201    return nullptr;
202}
203```
204
205ArkTS code:
206
207```ts
208import hilog from "@ohos.hilog"
209// Import the native APIs.
210import napitest from "libentry.so"
211try {
212  let script: string =
213  `
214      jsVmThrowTypeError()
215  `
216  napitest.runJsVm(script);
217} catch (error) {
218  hilog.error(0x0000, 'testTag', 'Test OH_JSVM_TypeError');
219}
220
221try {
222  let script: string =
223  `
224      jsVmThrowTypeError("has type Error")
225  `
226  napitest.runJsVm(script);
227} catch (error) {
228  hilog.error(0x0000, 'testTag', 'Test OH_JSVM_TypeError');
229}
230```
231
232### OH_JSVM_ThrowRangeError
233
234Use **OH_JSVM_ThrowRangeError** to throw a JS **RangeError** object with text information.
235
236CPP code:
237
238```cpp
239// hello.cpp
240#include "napi/native_api.h"
241#include "ark_runtime/jsvm.h"
242// Register the JsVmThrowRangeError callback.
243static JSVM_CallbackStruct param[] = {
244    {.data = nullptr, .callback = JsVmThrowRangeError},
245};
246static JSVM_CallbackStruct *method = param;
247// Set a property descriptor named jsVmThrowRangeError and associate it with a callback. This allows the JsVmThrowRangeError callback to be called from JS.
248static JSVM_PropertyDescriptor descriptor[] = {
249    {"jsVmThrowRangeError", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
250};
251static JSVM_Value JsVmThrowRangeError(JSVM_Env env, JSVM_CallbackInfo info)
252{
253    // Pass two parameters from JS.
254    size_t argc = 2;
255    JSVM_Value argv[2] = {nullptr};
256    OH_JSVM_GetCbInfo(env, info, &argc, argv, nullptr, nullptr);
257    // If the number of parameters is not 2,
258    if (argc != 2) {
259        // Throw a RangeError.
260        OH_JSVM_ThrowRangeError(env, "OH_JSVM_ThrowRangeError", "Expected two numbers as arguments");
261        return nullptr;
262    }
263    JSVM_Value result = nullptr;
264    OH_JSVM_GetBoolean(env, true, &result);
265    return result;
266}
267```
268
269ArkTS code:
270
271```ts
272import hilog from "@ohos.hilog"
273// Import the native APIs.
274import napitest from "libentry.so"
275try {
276  let script: string =
277  `
278      jsVmThrowRangeError(1)
279  `
280  napitest.runJsVm(script);
281} catch (error) {
282  hilog.error(0x0000, 'testTag', 'Test OH_JSVM_ThrowRangeError');
283}
284```
285
286### OH_JSVM_ThrowSyntaxError
287
288Use **OH_JSVM_ThrowSyntaxError** to throw a JS **SyntaxError** object with text information.
289
290CPP code:
291
292```cpp
293// hello.cpp
294#include "napi/native_api.h"
295#include "ark_runtime/jsvm.h"
296// Register the JsVmThrowSyntaxError callback.
297static JSVM_CallbackStruct param[] = {
298    {.data = nullptr, .callback = JsVmThrowSyntaxError},
299};
300static JSVM_CallbackStruct *method = param;
301// Set a property descriptor named jsVmThrowSyntaxError and associate it with a callback. This allows the JsVmThrowSyntaxError callback to be called from JS.
302static JSVM_PropertyDescriptor descriptor[] = {
303    {"jsVmThrowSyntaxError", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
304};
305static JSVM_Value JsVmThrowSyntaxError(JSVM_Env env, JSVM_CallbackInfo info) {
306    // Pass the JS code from JS.
307    size_t argc = 1;
308    JSVM_Value argv[1] = {nullptr};
309    OH_JSVM_GetCbInfo(env, info, &argc, argv, nullptr, nullptr);
310    JSVM_Script script = nullptr;
311    // Call OH_JSVM_CompileScript to compile the JS code.
312    OH_JSVM_CompileScript(env, argv[0], nullptr, 0, true, nullptr, &script);
313    JSVM_Value scriptResult = nullptr;
314    // Call OH_JSVM_RunScript to run the JS code.
315    JSVM_Status status = OH_JSVM_RunScript(env, script, &scriptResult);
316    if (status != JSVM_OK) {
317        // If the value returned by JSVM_RunScript is not JSVM_OK, throw a SyntaxError.
318        OH_JSVM_ThrowSyntaxError(env, "JsVmThrowSyntaxError", "throw syntax error");
319        return nullptr;
320    }
321    JSVM_Value result = nullptr;
322    OH_JSVM_GetBoolean(env, true, &result);
323    return result;
324}
325```
326
327ArkTS code:
328
329```ts
330import hilog from "@ohos.hilog"
331// Import the native APIs.
332import napitest from "libentry.so"
333try {
334    let script: string =` jsVmThrowSyntaxError()`
335    napitest.runJsVm(script);
336} catch(error) {
337    hilog.error(0x0000, 'testTag', 'Test jsVmThrowSyntaxError error message: %{public}s,', error.message);
338}
339```
340
341### OH_JSVM_IsError
342
343Use **OH_JSVM_IsError** to check whether the given **JSVM_Value** represents an error object.
344
345CPP code:
346
347```cpp
348// hello.cpp
349#include "napi/native_api.h"
350#include "ark_runtime/jsvm.h"
351// Register the JsVmIsError callback.
352static JSVM_CallbackStruct param[] = {
353    {.data = nullptr, .callback = JsVmIsError},
354};
355static JSVM_CallbackStruct *method = param;
356// Set a property descriptor named OH_JSVM_IsError and associate it with a callback. This allows the JsVmIsError callback to be called from JS.
357static JSVM_PropertyDescriptor descriptor[] = {
358    {"jsVmIsError", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
359};
360static JSVM_Value JsVmIsError(JSVM_Env env, JSVM_CallbackInfo info)
361{
362    size_t argc = 1;
363    JSVM_Value args[1] = {nullptr};
364    OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr);
365    // Call OH_JSVM_IsError to check whether the input parameter is an error object.
366    bool result = false;
367    // If JSVM_Value is an error object, set result to true. Otherwise, set result to false.
368    OH_JSVM_IsError(env, args[0], &result);
369    // Obtain result, call OH_JSVM_GetBoolean to convert result to JSVM_Value, and return JSVM_Value.
370    JSVM_Value returnValue = nullptr;
371    OH_JSVM_GetBoolean(env, result, &returnValue);
372    return returnValue;
373}
374```
375
376ArkTS code:
377
378```ts
379import hilog from "@ohos.hilog"
380// Import the native APIs.
381import napitest from "libentry.so"
382let script: string =
383  `
384      jsVmIsError(Error())
385  `
386const isError = napitest.runJsVm(script);
387hilog.info(0x0000, 'testTag', 'Test OH_JSVM_IsError error: %{public}s', isError);
388```
389
390### OH_JSVM_CreateTypeError
391
392Use **OH_JSVM_CreateTypeError** to create a JS **TypeError** object with text information.
393
394CPP code:
395
396```cpp
397// hello.cpp
398#include "napi/native_api.h"
399#include "ark_runtime/jsvm.h"
400#include <hilog/log.h>
401
402// Register the JsVmCreateTypeError callback.
403static JSVM_CallbackStruct param[] = {
404    {.data = nullptr, .callback = JsVmCreateTypeError},
405};
406static JSVM_CallbackStruct *method = param;
407// Set a property descriptor named jsVmCreateTypeError and associate it with a callback. This allows the JsVmCreateTypeError callback to be called from JS.
408static JSVM_PropertyDescriptor descriptor[] = {
409    {"jsVmCreateTypeError", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
410};
411static JSVM_Value JsVmCreateTypeError(JSVM_Env env, JSVM_CallbackInfo info) {
412    // Create a string in the JSVM and store it in the errorCode variable.
413    JSVM_Value errorCode = nullptr;
414    OH_JSVM_CreateStringUtf8(env, "-1", JSVM_AUTO_LENGTH, &errorCode);
415    // Create a string in the JSVM and store it in the errorMessage variable.
416    JSVM_Value errorMessage = nullptr;
417    OH_JSVM_CreateStringUtf8(env, "HasError", JSVM_AUTO_LENGTH, &errorMessage);
418    JSVM_Value result = nullptr;
419    JSVM_Status status = OH_JSVM_CreateTypeError(env, errorCode, errorMessage, &result);
420    if (status == JSVM_OK) {
421        OH_LOG_INFO(LOG_APP, "JSVM API Create TypeError SUCCESS");
422    } else {
423        OH_LOG_INFO(LOG_APP, "JSVM API Create TypeError FAILED");
424    }
425    return result;
426}
427```
428
429ArkTS code:
430
431```ts
432import hilog from "@ohos.hilog"
433// Import the native APIs.
434import napitest from "libentry.so"
435let script: string =`
436     jsVmCreateTypeError()
437  `
438napitest.runJsVm(script);
439```
440
441### OH_JSVM_CreateRangeError
442
443Use **OH_JSVM_CreateRangeError** to create a JS **RangeError** with text information.
444
445CPP code:
446
447```cpp
448// hello.cpp
449#include "napi/native_api.h"
450#include "ark_runtime/jsvm.h"
451#include <hilog/log.h>
452
453// Register the JsVmCreateRangeError callback.
454static JSVM_CallbackStruct param[] = {
455    {.data = nullptr, .callback = JsVmCreateRangeError},
456};
457static JSVM_CallbackStruct *method = param;
458// Set a property descriptor named jsVmCreateRangeError and associate it with a callback. This allows the JsVmCreateRangeError callback to be called from JS.
459static JSVM_PropertyDescriptor descriptor[] = {
460    {"jsVmCreateRangeError", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
461};
462static JSVM_Value JsVmCreateRangeError(JSVM_Env env, JSVM_CallbackInfo info) {
463    // Create a string in the JSVM and store it in the errorCode variable.
464    JSVM_Value errorCode = nullptr;
465    OH_JSVM_CreateStringUtf8(env, "-1", JSVM_AUTO_LENGTH, &errorCode);
466    // Create a string in the JSVM and store it in the errorMessage variable.
467    JSVM_Value errorMessage = nullptr;
468    OH_JSVM_CreateStringUtf8(env, "HasError", JSVM_AUTO_LENGTH, &errorMessage);
469    JSVM_Value result = nullptr;
470    JSVM_Status status = OH_JSVM_CreateRangeError(env, errorCode, errorMessage, &result);
471    if (status == JSVM_OK) {
472        OH_LOG_INFO(LOG_APP, "JSVM API CreateRangeError SUCCESS");
473    } else {
474        OH_LOG_INFO(LOG_APP, "JSVM API CreateRangeError FAILED");
475    }
476    return result;
477}
478```
479
480ArkTS code:
481
482```ts
483import hilog from "@ohos.hilog"
484// Import the native APIs.
485import napitest from "libentry.so"
486let script: string =
487   `
488    jsVmCreateRangeError()
489   `
490napitest.runJsVm(script);
491```
492
493### OH_JSVM_CreateSyntaxError
494
495CPP code:
496
497```cpp
498// hello.cpp
499#include "napi/native_api.h"
500#include "ark_runtime/jsvm.h"
501#include <hilog/log.h>
502
503
504// Register the JsVmCreateSyntaxError callback.
505static JSVM_CallbackStruct param[] = {
506    {.data = nullptr, .callback = JsVmCreateSyntaxError},
507};
508static JSVM_CallbackStruct *method = param;
509// Set a property descriptor named jsVmThrow and associate it with a callback. This allows the JsVmThrow callback to be called from JS.
510static JSVM_PropertyDescriptor descriptor[] = {
511    {"jsVmCreateSyntaxError", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
512};
513static JSVM_Value JsVmCreateSyntaxError(JSVM_Env env, JSVM_CallbackInfo info) {
514    // Create a string in the JSVM and store it in the errorCode variable.
515    JSVM_Value errorCode = nullptr;
516    OH_JSVM_CreateStringUtf8(env, "-1", JSVM_AUTO_LENGTH, &errorCode);
517    // Create a string in the JSVM and store it in the errorMessage variable.
518    JSVM_Value errorMessage = nullptr;
519    OH_JSVM_CreateStringUtf8(env, "HasError", JSVM_AUTO_LENGTH, &errorMessage);
520    JSVM_Value result = nullptr;
521    JSVM_Status status =  OH_JSVM_CreateSyntaxError(env, errorCode, errorMessage, &result);
522    if (status == JSVM_OK) {
523        OH_LOG_INFO(LOG_APP, "JSVM API CreateSyntaxError SUCCESS");
524    } else {
525        OH_LOG_INFO(LOG_APP, "JSVM API CreateSyntaxError FAILED");
526    }
527    return result;
528}
529```
530
531ArkTS code:
532
533```ts
534import hilog from "@ohos.hilog"
535// Import the native APIs.
536import napitest from "libentry.so"
537let script: string =
538  `
539  let error = jsVmCreateSyntaxError()
540  `
541napitest.runJsVm(script);
542```
543
544### OH_JSVM_GetAndClearLastException
545
546Use **OH_JSVM_GetAndClearLastException** to obtain and clear the latest exception.
547
548CPP code:
549
550```cpp
551// hello.cpp
552#include "napi/native_api.h"
553#include "ark_runtime/jsvm.h"
554#include <hilog/log.h>
555
556// Register the JsVmGetAndClearLastException callback.
557static JSVM_CallbackStruct param[] = {
558    {.data = nullptr, .callback = JsVmGetAndClearLastException},
559};
560static JSVM_CallbackStruct *method = param;
561// Set a property descriptor named jsVmGetAndClearLastException and associate it with a callback. This allows the JsVmGetAndClearLastException callback to be called from JS.
562static JSVM_PropertyDescriptor descriptor[] = {
563    {"jsVmGetAndClearLastException", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
564};
565static JSVM_Value JsVmGetAndClearLastException(JSVM_Env env, JSVM_CallbackInfo info) {
566    // Throw an error.
567    OH_JSVM_ThrowError(env, "OH_JSVM_ThrowError errorCode", "OH_JSVM_ThrowError errorMessage");
568    // Call OH_JSVM_GetAndClearLastException to obtain and clear the last exception. This API can also be used to handle a suspended JS exception.
569    JSVM_Value result = nullptr;
570    JSVM_Status status = OH_JSVM_GetAndClearLastException(env, &result);
571    if (status != JSVM_OK) {
572        OH_LOG_INFO(LOG_APP, "JSVM API OH_JSVM_GetAndClearLastException FAILED");
573    } else {
574        OH_LOG_INFO(LOG_APP, "JSVM API OH_JSVM_GetAndClearLastException SUCCESS");
575    }
576    return result;
577}
578```
579
580ArkTS code:
581
582```ts
583import hilog from "@ohos.hilog"
584// Import the native APIs.
585import napitest from "libentry.so"
586let script: string =
587 `
588   jsVmGetAndClearLastException()
589`
590napitest.runJsVm(script);
591```
592
593### OH_JSVM_IsExceptionPending
594
595Use **OH_JSVM_IsExceptionPending** to check whether there is any pending exception.
596
597CPP code:
598
599```cpp
600// hello.cpp
601#include "napi/native_api.h"
602#include "ark_runtime/jsvm.h"
603#include <hilog/log.h>
604
605// Register the JsVmIsExceptionPending callback.
606static JSVM_CallbackStruct param[] = {
607    {.data = nullptr, .callback = JsVmIsExceptionPending},
608};
609static JSVM_CallbackStruct *method = param;
610// Set a property descriptor named jsVmIsExceptionPending and associate it with a callback. This allows the JsVmIsExceptionPending callback to be called from JS.
611static JSVM_PropertyDescriptor descriptor[] = {
612    {"jsVmIsExceptionPending", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
613};
614static JSVM_Value JsVmIsExceptionPending(JSVM_Env env, JSVM_CallbackInfo info) {
615    JSVM_Status status;
616    bool isExceptionPending = false;
617    // Perform operations that may cause an error.
618    OH_JSVM_ThrowError(env, "OH_JSVM_ThrowError errorCode", "OH_JSVM_ThrowError errorMessage");
619    // Check whether there is a pending exception.
620    status = OH_JSVM_IsExceptionPending(env, &isExceptionPending);
621    if (status != JSVM_OK) {
622        return nullptr;
623    }
624    if (isExceptionPending) {
625        OH_LOG_INFO(LOG_APP, "JSVM API OH_JSVM_IsExceptionPending: SUCCESS");
626        // Handle the pending exception.
627        JSVM_Value result = nullptr;
628        status = OH_JSVM_GetAndClearLastException(env, &result);
629        if (status != JSVM_OK) {
630            return nullptr;
631        }
632        // Return the result.
633        return result;
634    } else {
635        OH_LOG_INFO(LOG_APP, "JSVM API OH_JSVM_IsExceptionPending: FAILED");
636    }
637    return nullptr;
638}
639```
640
641ArkTS code:
642
643```ts
644import hilog from "@ohos.hilog"
645// Import the native APIs.
646import napitest from "libentry.so"
647let script: string =
648              `
649    let error = jsVmIsExceptionPending()
650    `
651napitest.runJsVm(script);
652```
653
654### OH_JSVM_GetLastErrorInfo
655
656Use **OH_JSVM_GetLastErrorInfo** to obtain the last error information, including the error code, error message, and stack information. This API can also be used to handle pending JS exceptions.
657
658CPP code:
659
660```cpp
661// hello.cpp
662#include "napi/native_api.h"
663#include "ark_runtime/jsvm.h"
664#include <hilog/log.h>
665
666// Register the JsVmGetLastErrorInfo callback.
667static JSVM_CallbackStruct param[] = {
668    {.data = nullptr, .callback = JsVmGetLastErrorInfo},
669};
670static JSVM_CallbackStruct *method = param;
671// Set a property descriptor named jsVmGetLastErrorInfo and associate it with a callback. This allows the JsVmGetLastErrorInfo callback to be called from JS.
672static JSVM_PropertyDescriptor descriptor[] = {
673    {"jsVmGetLastErrorInfo", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
674};
675static JSVM_Value JsVmGetLastErrorInfo(JSVM_Env env, JSVM_CallbackInfo info) {
676    // Obtain the input parameter, that is the message string in this example.
677    size_t argc = 1;
678    JSVM_Value args[1] = {nullptr};
679    OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr);
680    // Call OH_JSVM_GetValueInt32 to obtain the input string parameter to create an error.
681    int32_t value = 0;
682     OH_JSVM_GetValueInt32(env, args[0], &value);
683    // Call OH_JSVM_GetLastErrorInfo to obtain the last error message.
684    const JSVM_ExtendedErrorInfo *errorInfo;
685    OH_JSVM_GetLastErrorInfo(env, &errorInfo);
686    // Obtain the error message as the return value and print it.
687    JSVM_Value result = nullptr;
688    OH_LOG_INFO(LOG_APP, "JSVM API OH_JSVM_GetLastErrorInfo: SUCCESS");
689
690    OH_JSVM_CreateInt32(env, errorInfo->errorCode, &result);
691    return result;
692}
693```
694
695ArkTS code:
696
697```ts
698import hilog from "@ohos.hilog"
699// Import the native APIs.
700import napitest from "libentry.so"
701let script: string = `jsVmGetLastErrorInfo()`
702napitest.runJsVm(script);
703```
704