繁体   English   中英

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

[英]Throwing a JavaScript exception from C++ code using Google 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);
...

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

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

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

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


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

您还可以使用v8::Exception的静态函数抛出更具体的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的最新版本中,Mattew的答案不起作用。 现在,在您使用的每个函数中,都会获得一个Isolate对象。

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

Isolate* isolate = Isolate::GetCurrent();
isolate->ThrowException(String::NewFromUtf8(isolate, "error string here"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM