nodejs C++ module 在 init 中失败

nodejs C++ module fail in init

本文关键字:失败 init C++ module nodejs      更新时间:2023-10-16

我正在编写一个nodejs C++模块,在我的init函数内部,我进行了一次可能会失败的系统调用。 失败时,我希望它向解释器抛出异常来处理,而是得到一个赛段错误。 如何获得正确的行为?

所以例如,我有类似的东西:

//...
void Init(Handle<Object> target) {
  if (my_setup_io()==FAIL_CODITION){
    ThrowException(Exception::Error(
      String::New("Could not init ")));  //SEG fault instead of exception
  }
  target->Set(String::NewSymbol("myFunction"),
      FunctionTemplate::New(myFunction)->GetFunction());
 }
NODE_MODULE(example, Init)

主要问题是ThrowException在 JS 中触发异常,但它实际上并没有触发C++异常。这意味着代码将在异常运行后尝试运行Set

如果您在安排 JS 抛出后返回,它应该可以正常工作。

void Init(Handle<Object> target) {
  if (my_setup_io()==FAIL_CODITION){
    ThrowException(Exception::Error(String::New("Could not init ")));
    return; // RETURN!
  }
  target->Set(String::NewSymbol("myFunction"),
    FunctionTemplate::New(myFunction)->GetFunction());
}
NODE_MODULE(example, Init)