Skip to content

Commit eb29266

Browse files
mhdawsonMylesBorins
authored andcommitted
n-api: add missing exception checking
Add checks for a pending exception in napi_make_callback after the callback has been invoked. If there is a pending exception then we need to avoid checking the result as that will not be able to complete properly. Add additional checks to the unit test for napi_make_callback to catch this case. Backport-PR-URL: #19447 PR-URL: #19362 Fixes: nodejs/node-addon-api#235 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Anna Henningsen <[email protected]>
1 parent b9b752e commit eb29266

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

src/node_api.cc

+8-4
Original file line numberDiff line numberDiff line change
@@ -2910,11 +2910,15 @@ napi_status napi_make_callback(napi_env env,
29102910
isolate, v8recv, v8func, argc,
29112911
reinterpret_cast<v8::Local<v8::Value>*>(const_cast<napi_value*>(argv)),
29122912
*node_async_context);
2913-
CHECK_MAYBE_EMPTY(env, callback_result, napi_generic_failure);
29142913

2915-
if (result != nullptr) {
2916-
*result = v8impl::JsValueFromV8LocalValue(
2917-
callback_result.ToLocalChecked());
2914+
if (try_catch.HasCaught()) {
2915+
return napi_set_last_error(env, napi_pending_exception);
2916+
} else {
2917+
CHECK_MAYBE_EMPTY(env, callback_result, napi_generic_failure);
2918+
if (result != nullptr) {
2919+
*result = v8impl::JsValueFromV8LocalValue(
2920+
callback_result.ToLocalChecked());
2921+
}
29182922
}
29192923

29202924
return GET_RETURN_STATUS(env);

test/addons-napi/test_make_callback_recurse/binding.cc

+14-1
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,22 @@ napi_value MakeCallback(napi_env env, napi_callback_info info) {
1212
napi_value recv = args[0];
1313
napi_value func = args[1];
1414

15-
napi_make_callback(env, nullptr /* async_context */,
15+
napi_status status = napi_make_callback(env, nullptr /* async_context */,
1616
recv, func, 0 /* argc */, nullptr /* argv */, nullptr /* result */);
1717

18+
bool isExceptionPending;
19+
NAPI_CALL(env, napi_is_exception_pending(env, &isExceptionPending));
20+
if (isExceptionPending && !(status == napi_pending_exception)) {
21+
// if there is an exception pending we don't expect any
22+
// other error
23+
napi_value pending_error;
24+
status = napi_get_and_clear_last_exception(env, &pending_error);
25+
NAPI_CALL(env,
26+
napi_throw_error((env),
27+
nullptr,
28+
"error when only pending exception expected"));
29+
}
30+
1831
return recv;
1932
}
2033

0 commit comments

Comments
 (0)