Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing a JavaScript exception from C++ code using Google V8

Tags:

c++

javascript

v8

I'm programming a JavaScript application which accesses some C++ code over Google's V8.

Everything works fine, but I couldn't figure out how I can throw a JavaScript exception which can be catched in the JavaScript code from the C++ method.

For example, if I have a function in C++ like

... 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); ... 

exposed to JavaScript, I'ld like to use it in the JavaScript code like

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

What is the correct way to throw a V8-exception out of the C++ code?

like image 590
Etan Avatar asked Sep 02 '09 09:09

Etan


2 Answers

Edit: This answer is for older versions of V8. For current versions, see Sutarmin Anton's Answer.


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

You can also throw a more specific exception with the static functions in 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("..."))); 
like image 61
Matthew Crumley Avatar answered Oct 09 '22 03:10

Matthew Crumley


In last versions of v8 Mattew's answer doesn't work. Now in every function that you use you get an Isolate object.

New exception raising with Isolate object look like this:

Isolate* isolate = Isolate::GetCurrent(); isolate->ThrowException(String::NewFromUtf8(isolate, "error string here")); 
like image 23
Anton Sutarmin Avatar answered Oct 09 '22 03:10

Anton Sutarmin