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

Eta*_*tan 26 javascript c++ v8

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

一切正常,但我无法弄清楚如何抛出JavaScript异常,这可以从C++方法的JavaScript代码中获取.

例如,如果我有像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);
...
Run Code Online (Sandbox Code Playgroud)

暴露在JavaScript中,我想在JavaScript代码中使用它

try {
    hello("throw me some exception!");
} catch (e) {
    // catched it!
}
Run Code Online (Sandbox Code Playgroud)

从C++代码中抛出V8异常的正确方法是什么?

Mat*_*ley 29

编辑:此答案适用于旧版本的V8.对于当前版本,请参阅Sutarmin Anton的答案.


return v8::ThrowException(v8::String::New("Exception message"));
Run Code Online (Sandbox Code Playgroud)

您还可以使用以下静态函数抛出更具体的异常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("...")));
Run Code Online (Sandbox Code Playgroud)

  • 在我的C++函数返回JS之后,我得到了"Segmentation fault" (4认同)

Ant*_*min 14

在v8的最新版本中,Mattew的答案不起作用.现在,在您使用的每个函数中,都会获得一个Isolate对象.

使用Isolate对象的新异常提升如下所示:

Isolate* isolate = Isolate::GetCurrent();
isolate->ThrowException(String::NewFromUtf8(isolate, "error string here"));
Run Code Online (Sandbox Code Playgroud)