簡體   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