节点 API 抛出它自己的错误消息而不是自己的错误消息

Node API throws it's own error message instead of own error message

我正在尝试为 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.Now 我想处理用户未提供的情况我的函数的任何参数或(一个或两个)参数都不是 number.In 这种情况下我想抛出自定义消息("You didn't provide 2 numbers")。但是当我尝试从 [=34= 调用我的方法时] 没有任何参数我得到以下错误:

console.log(addon.add());
                  ^

Error: A number was expected

为什么我收到这条特定消息而不是我在 if 块中写的消息?

以下是我导出函数的方式:

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 中禁用了 C++ 异常(cflags/cflags_cc="-fno-exceptions",定义:" NAPI_DISABLE_CPP_EXCEPTIONS") 你应该阅读 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++ 异常,因此如果您不 return.

,您的 C++ 函数将继续 运行