Skip to content

Commit d181f7f

Browse files
committed
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. Fixes: nodejs/node-addon-api#235
1 parent cd7d7b1 commit d181f7f

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
@@ -2801,11 +2801,15 @@ napi_status napi_make_callback(napi_env env,
28012801
isolate, v8recv, v8func, argc,
28022802
reinterpret_cast<v8::Local<v8::Value>*>(const_cast<napi_value*>(argv)),
28032803
*node_async_context);
2804-
CHECK_MAYBE_EMPTY(env, callback_result, napi_generic_failure);
28052804

2806-
if (result != nullptr) {
2807-
*result = v8impl::JsValueFromV8LocalValue(
2808-
callback_result.ToLocalChecked());
2805+
if (try_catch.HasCaught()) {
2806+
return napi_set_last_error(env, napi_pending_exception);
2807+
} else {
2808+
CHECK_MAYBE_EMPTY(env, callback_result, napi_generic_failure);
2809+
if (result != nullptr) {
2810+
*result = v8impl::JsValueFromV8LocalValue(
2811+
callback_result.ToLocalChecked());
2812+
}
28092813
}
28102814

28112815
return GET_RETURN_STATUS(env);

test/addons-napi/test_make_callback_recurse/binding.cc

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

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

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

0 commit comments

Comments
 (0)