本文讲述如何利用v8::TryCatch捕捉js代码中发生的异常。
首先,声明TryCatch对象。
v8::TryCatch trycatch( isolate );
然后,定义抛出异常的函数:
void ThrowException( const v8::FunctionCallbackInfo<v8::Value>& info ) {
v8::Isolate* isolate = info.GetIsolate();
v8::HandleScope scope( isolate );
v8::Local<v8::Value> exc = v8::Local<v8::Value>::New( info.GetIsolate(),
v8::Exception::Error( v8::String::NewFromUtf8( isolate, "throw an exception" ).ToLocalChecked() ) );
info.GetIsolate()->ThrowException( exc );
}
设置访问器访问C++函数:
v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New( isolate );
global->Set( isolate, "throwException",
v8::FunctionTemplate::New( isolate, ThrowException ) );
因为异常发生在执行js文件期间,所以需要在Run函数后判断是否有异常