I'm writing a nodejs C++ module and inside of my init function I have make a system call that may fail. On failing I want it to throw an exception to the interpreter to deal with but instead a get a seg-fault. How do I get the correct behavior?
so for example I have something similar to:
//...
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)
The main issue is ThrowException triggers an exception in JS, but it does not actually trigger a C++ exception. That means that your code will attempt to run Set after the exception runs.
It should work fine if you return after scheduling the JS throw.
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)