Nan::TryCatch 不会拦截 JS 代码在 Nan::Callback 中抛出的异常

Nan::TryCatch will not intercept exception thrown in Nan::Callback from JS code

假设我有一个 JS 函数,它只是抛出一个错误:

function() { throw "Danger, Will Robinson!"; }

此函数作为参数传递给 node.js 插件并用于构建 Nan::Callback(应该负责使此句柄持久化):

// get handle to JS function and its Tcl name Handle<Function> fun = Handle<Function>::Cast( info[0] ); Nan::Callback *pf = new Nan::Callback(fun);

当使用 C++ 中的 Call() 调用 Nan::Callback 时,我在从 C++ 中拦截 拦截 此 JS 异常时遇到问题:

Nan::TryCatch tc; Local<Value> retv = pf->Call( Nan::GetCurrentContext()->Global(), objc-1, &args ); if ( tc.HasCaught() ) { printf("EXCEPTION:\n"); ...

事实上,脚本只是在出现 JS 错误时退出,我再也没有回来检查 tc 和调用 return 值 (retv) 以查找任何未决异常。我做错了什么?

找到了,这很有可能是known Nan bug。引用 hankbao 7 月 27 日的评论:

I've just encountered a related issue. We're currently using electron to pack our web app. There's a native node addon providing some functionality for the electron app. Our web app will call the addon and pass a js callback to it. The native addon store the callback in a NanCallback. It setups a TryCatch before calling the callback. However the TryCatch always fails to catch the exception thrown by the js callback. It turns out that if I call the callback with Function::Call instead of with NanCallback::Call(), exceptions can be caught

根据这个提示,我解决了问题:我用v8::Persistent<Function>替换了Nan::Callback的函数句柄,最后得到了[=12] =] 按预期工作。唯一的问题:不使用 Nan 意味着代码很容易被破坏,因为 v8 随着时间的推移并不是完全稳定的 API :)