我正在尝试为 NAPI
编写以下函数。
int addon::fakeAdd(int a, int b)
{
return a + b;
}
Napi::Number addon::addWrapped(const Napi::CallbackInfo &info)
{
Napi::Env env = info.Env();
if (info.Length() < 2 || !info[0].IsNumber() || !info[1].IsNumber())
{
auto x = Napi::TypeError::New(env, "You did not provide 2 numbers");
x.ThrowAsJavaScriptException();
}
Napi::Number num1 = info[0].As<Napi::Number>();
Napi::Number num2 = info[1].As<Napi::Number>();
int returnValue = addon::fakeAdd(num1.Int32Value(), num2.Int32Value());
return Number::New(env, returnValue);
}
我将此函数导出为 add
。当我使用参数(例如 addon.add(1,2)
)从 javascript 调用它时,一切都很好用,我得到了正确的结果 3。现在我想处理以下情况用户没有为我的函数提供任何参数,或者(一个或两个)参数不是数字。在那种情况下,我想抛出一条自定义消息(“你没有提供 2 个数字”)。但是当我尝试调用我的没有任何参数的 JavaScript 方法我收到以下错误:
console.log(addon.add());
^
Error: A number was expected
我收到此特定消息而不是我在 if
block 中编写的消息是否有原因?
这是我导出函数的方式:
Napi::Object addon::Init(Napi::Env env, Napi::Object exports)
{
exports.Set("add", Napi::Function::New(env, addon::addWrapped));
exports.Set("getOsName", Napi::Function::New(env, addon::getOSNameWrapped));
exports.Set("writeToFile", Napi::Function::New(env, addon::writeFileWrapped));
return exports;
}
这里是binding.gyp文件
{
"targets": [{
"target_name": "testaddon",
"cflags!": [ "-fno-exceptions"],
"cflags_cc!": [ "-fno-exceptions" ],
"cflags_cc":["-std=c++1z" ],
"sources": [
"cppsrc/main.cpp",
"cppsrc/functionexample.cpp"
],
'include_dirs': [
"<!@(node -p \"require('node-addon-api').include\")"
],
'libraries': [],
'dependencies': [
"<!(node -p \"require('node-addon-api').gyp\")"
],
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ]
}]
}
最佳答案
假设您在 binding.gyp (cflags/cflags_cc="-fno-exceptions", defines:"NAPI_DISABLE_CPP_EXCEPTIONS") 中禁用了 C++ 异常,您应该阅读 this section of the error handling documentation :
After throwing a JavaScript exception, the code should generally return immediately from the native callback, after performing any necessary cleanup.
他们的例子:
Napi::Error::New(env, "Example exception").ThrowAsJavaScriptException();
return;
调用 ThrowAsJavaScriptException() 不会抛出 C++ 异常,因此如果您不返回,您的 C++ 函数将继续运行。
关于c++ - Node API 抛出它自己的错误消息而不是自己的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57733209/