File: error_handling.md

package info (click to toggle)
node-addon-api 8.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,248 kB
  • sloc: cpp: 15,431; javascript: 5,631; ansic: 157; makefile: 7
file content (266 lines) | stat: -rw-r--r-- 10,730 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# Error handling

Error handling represents one of the most important considerations when
implementing a Node.js native add-on. When an error occurs in your C++ code you
have to handle and dispatch it correctly. **node-addon-api** uses return values and
JavaScript exceptions for error handling. You can choose return values or
exception handling based on the mechanism that works best for your add-on.

The `Napi::Error` is a persistent reference (for more info see: [`Napi::ObjectReference`](object_reference.md))
to a JavaScript error object. Use of this class depends on whether C++
exceptions are enabled at compile time.

If C++ exceptions are enabled (for more info see: [Setup](setup.md)), then the
`Napi::Error` class extends `std::exception` and enables integrated
error-handling for C++ exceptions and JavaScript exceptions.

Note, that due to limitations of the Node-API, if one attempts to cast the error object wrapping a primitive inside a C++ addon, the wrapped object
will be received instead. (With property `4bda9e7e-4913-4dbc-95de-891cbf66598e-errorVal` containing the primitive value thrown)

The following sections explain the approach for each case:

- [Handling Errors With C++ Exceptions](#exceptions)
- [Handling Errors With Maybe Type and C++ Exceptions Disabled](#noexceptions-maybe)
- [Handling Errors Without C++ Exceptions](#noexceptions)

<a name="exceptions"></a>

In most cases when an error occurs, the addon should do whatever cleanup is possible
and then return to JavaScript so that the error can be propagated. In less frequent
cases the addon may be able to recover from the error, clear the error and then
continue.

## Handling Errors With C++ Exceptions

When C++ exceptions are enabled try/catch can be used to catch exceptions thrown
from calls to JavaScript and then they can either be handled or rethrown before
returning from a native method.

If a node-addon-api call fails without executing any JavaScript code (for example due to
an invalid argument), then node-addon-api automatically converts and throws
the error as a C++ exception of type `Napi::Error`.

If a JavaScript function called by C++ code via node-addon-api throws a JavaScript
exception, then node-addon-api automatically converts and throws it as a C++
exception of type `Napi::Error` on return from the JavaScript code to the native
method.

If a C++ exception of type `Napi::Error` escapes from a Node-API C++ callback, then
the Node-API wrapper automatically converts and throws it as a JavaScript exception.

If other types of C++ exceptions are thrown, node-addon-api will either abort
the process or wrap the exception in an `Napi::Error` in order to throw it as a
JavaScript exception. This behavior is determined by which node-gyp dependency
used:

- When using the `node_addon_api_except` dependency, only `Napi::Error` objects
  will be handled.
- When using the `node_addon_api_except_all` dependency, all exceptions will be
handled. For exceptions derived from `std::exception`, an `Napi::Error` will be
created with the message of the exception's `what()` member function. For all
other exceptions, an `Napi::Error` will be created with a generic error message.

On return from a native method, node-addon-api will automatically convert a pending
`Napi::Error` C++ exception to a JavaScript exception.

When C++ exceptions are enabled try/catch can be used to catch exceptions thrown
from calls to JavaScript and then they can either be handled or rethrown before
returning from a native method.

## Examples with C++ exceptions enabled

### Throwing a C++ exception

```cpp
Env env = ...
throw Napi::Error::New(env, "Example exception");
// other C++ statements
// ...
```

The statements following the throw statement will not be executed. The exception
will bubble up as a C++ exception of type `Napi::Error`, until it is either caught
while still in C++, or else automatically propagated as a JavaScript exception
when returning to JavaScript.

### Propagating a Node-API C++ exception

```cpp
Napi::Function jsFunctionThatThrows = someValue.As<Napi::Function>();
Napi::Value result = jsFunctionThatThrows({ arg1, arg2 });
// other C++ statements
// ...
```

The C++ statements following the call to the JavaScript function will not be
executed. The exception will bubble up as a C++ exception of type `Napi::Error`,
until it is either caught while still in C++, or else automatically propagated as
a JavaScript exception when returning to JavaScript.

### Handling a Node-API C++ exception

```cpp
Napi::Function jsFunctionThatThrows = someValue.As<Napi::Function>();
Napi::Value result;
try {
    result = jsFunctionThatThrows({ arg1, arg2 });
} catch (const Error& e) {
    cerr << "Caught JavaScript exception: " + e.what();
}
```

Since the exception was caught here, it will not be propagated as a JavaScript
exception.

<a name="noexceptions-maybe"></a>

## Handling Errors With Maybe Type and C++ Exceptions Disabled

If C++ exceptions are disabled (for more info see: [Setup](setup.md)), then the
`Napi::Error` class does not extend `std::exception`. This means that any calls to
node-addon-api functions do not throw a C++ exceptions. Instead, these node-api
functions that call into JavaScript are returning with `Maybe` boxed values.
In that case, the calling side should convert the `Maybe` boxed values with
checks to ensure that the call did succeed and therefore no exception is pending.
If the check fails, that is to say, the returning value is _empty_, the calling
side should determine what to do with `env.GetAndClearPendingException()` before
attempting to call another node-api (for more info see: [Env](env.md)).

The conversion from the `Maybe` boxed value to the actual return value is
enforced by compilers so that the exceptions must be properly handled before
continuing.

## Examples with Maybe Type and C++ exceptions disabled

### Throwing a JS exception

```cpp
Napi::Env env = ...
Napi::Error::New(env, "Example exception").ThrowAsJavaScriptException();
return;
```

After throwing a JavaScript exception, the code should generally return
immediately from the native callback, after performing any necessary cleanup.

### Propagating a Node-API JS exception

```cpp
Napi::Env env = ...
Napi::Function jsFunctionThatThrows = someValue.As<Napi::Function>();
Maybe<Napi::Value> maybeResult = jsFunctionThatThrows({ arg1, arg2 });
Napi::Value result;
if (!maybeResult.To(&result)) {
    // The Maybe is empty, calling into js failed, cleaning up...
    // It is recommended to return an empty Maybe if the procedure failed.
    return result;
}
```

If `maybeResult.To(&result)` returns false a JavaScript exception is pending.
To let the exception propagate, the code should generally return immediately
from the native callback, after performing any necessary cleanup.

### Handling a Node-API JS exception

```cpp
Napi::Env env = ...
Napi::Function jsFunctionThatThrows = someValue.As<Napi::Function>();
Maybe<Napi::Value> maybeResult = jsFunctionThatThrows({ arg1, arg2 });
if (maybeResult.IsNothing()) {
    Napi::Error e = env.GetAndClearPendingException();
    cerr << "Caught JavaScript exception: " + e.Message();
}
```

Since the exception was cleared here, it will not be propagated as a JavaScript
exception after the native callback returns.

<a name="noexceptions"></a>

## Handling Errors Without C++ Exceptions

If C++ exceptions are disabled (for more info see: [Setup](setup.md)), then the
`Napi::Error` class does not extend `std::exception`. This means that any calls to
node-addon-api function do not throw a C++ exceptions. Instead, it raises
_pending_ JavaScript exceptions and returns an _empty_ `Napi::Value`.
The calling code should check `env.IsExceptionPending()` before attempting to use a
returned value, and may use methods on the `Napi::Env` class
to check for, get, and clear a pending JavaScript exception (for more info see: [Env](env.md)).
If the pending exception is not cleared, it will be thrown when the native code
returns to JavaScript.

## Examples with C++ exceptions disabled

### Throwing a JS exception

```cpp
Napi::Env env = ...
Napi::Error::New(env, "Example exception").ThrowAsJavaScriptException();
return;
```

After throwing a JavaScript exception, the code should generally return
immediately from the native callback, after performing any necessary cleanup.

### Propagating a Node-API JS exception

```cpp
Napi::Env env = ...
Napi::Function jsFunctionThatThrows = someValue.As<Napi::Function>();
Napi::Value result = jsFunctionThatThrows({ arg1, arg2 });
if (env.IsExceptionPending()) {
    Error e = env.GetAndClearPendingException();
    return e.Value();
}
```

If env.IsExceptionPending() returns true a JavaScript exception is pending. To
let the exception propagate, the code should generally return immediately from
the native callback, after performing any necessary cleanup.

### Handling a Node-API JS exception

```cpp
Napi::Env env = ...
Napi::Function jsFunctionThatThrows = someValue.As<Napi::Function>();
Napi::Value result = jsFunctionThatThrows({ arg1, arg2 });
if (env.IsExceptionPending()) {
    Napi::Error e = env.GetAndClearPendingException();
    cerr << "Caught JavaScript exception: " + e.Message();
}
```

Since the exception was cleared here, it will not be propagated as a JavaScript
exception after the native callback returns.

## Calling Node-API directly from a **node-addon-api** addon

**node-addon-api** provides macros for throwing errors in response to non-OK
`napi_status` results when calling [Node-API](https://nodejs.org/docs/latest/api/n-api.html)
functions from within a native addon. These macros are defined differently
depending on whether C++ exceptions are enabled or not, but are available for
use in either case.

### `NAPI_THROW(e, ...)`

This macro accepts a `Napi::Error`, throws it, and returns the value given as
the last parameter. If C++ exceptions are enabled (by defining
`NAPI_CPP_EXCEPTIONS` during the build), the return value will be ignored.

### `NAPI_THROW_IF_FAILED(env, status, ...)`

This macro accepts a `Napi::Env` and a `napi_status`. It constructs an error
from the `napi_status`, throws it, and returns the value given as the last
parameter. If C++ exceptions are enabled (by defining `NAPI_CPP_EXCEPTIONS`
during the build), the return value will be ignored.

### `NAPI_THROW_IF_FAILED_VOID(env, status)`

This macro accepts a `Napi::Env` and a `napi_status`. It constructs an error
from the `napi_status`, throws it, and returns.

### `NAPI_FATAL_IF_FAILED(status, location, message)`

This macro accepts a `napi_status`, a C string indicating the location where the
error occurred, and a second C string for the message to display.