使用Google V8从C++代码抛出JavaScript异常

26

我正在编写一个JavaScript应用程序,通过Google的V8访问一些C++代码。

一切运行正常,但我无法弄清如何抛出JavaScript异常,并在JavaScript代码中捕获该异常,而这个异常是从C++方法中抛出的。

例如,如果我有一个C++函数:

...
using namespace std;
using namespace v8;
...
static Handle<Value> jsHello(const Arguments& args) {
    String::Utf8Value input(args[0]);
    if (input == "Hello") {
        string result = "world";
        return String::New(result.c_str());
    } else {
        // throw exception
    }
}
...
    global->Set(String::New("hello"), FunctionTemplate::New(jsHello));
    Persistent<Context> context = Context::New(NULL, global);
...

暴露给JavaScript后,我想在JavaScript代码中使用它,如:

try {
    hello("throw me some exception!");
} catch (e) {
    // catched it!
}

如何在C++代码中正确地抛出V8异常?

2个回答

29

编辑:此答案适用于较旧版本的V8。有关当前版本,请参见Sutarmin Anton's Answer


return v8::ThrowException(v8::String::New("Exception message"));

你还可以使用v8::Exception中的静态函数抛出更具体的异常:

return v8::ThrowException(v8::Exception::RangeError(v8::String::New("...")));
return v8::ThrowException(v8::Exception::ReferenceError(v8::String::New("...")));
return v8::ThrowException(v8::Exception::SyntaxError(v8::String::New("...")));
return v8::ThrowException(v8::Exception::TypeError(v8::String::New("...")));
return v8::ThrowException(v8::Exception::Error(v8::String::New("...")));

谢谢!我过去三周一直在阅读V8 API,但不知何故错过了这个。 - Vortico
4
我的C++函数返回到JS后会出现“分段错误”。 - exebook

15
在v8的最新版本中,Mattew的答案不再适用。现在,在您使用的每个函数中,您都会得到一个Isolate对象。
使用带有Isolate对象的新异常抛出看起来像这样:
Isolate* isolate = Isolate::GetCurrent();
isolate->ThrowException(String::NewFromUtf8(isolate, "error string here"));

1
isolate->ThrowException(v8::Exception::RangeError(String::NewFromUtf8(isolate, "error string here")));(哇,我只会使用_Nan_。) - Константин Ван

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接