void JSAttributeTest::requestValueWithCallbackTestOnlyFirstTime(std::shared_ptr<JSZAttribute> &jsZAttribute, std::shared_ptr<ZCLAttribute> attributeMock, Callbacks &changeSignal) { ZDevice zDevice{createZDevice()}; std::stringstream stream; stream << "var f = function (){\n"; stream << " var log = Log();\n"; stream << " log.info('callback called')"; stream << "};\n"; stream << zAttributeVariable << "\n"; stream << "var b = a.requestValue(f);\n"; V8_SETUP jsZAttribute->initJsObjectsTemplate(isolate, global); jsLog->initJsObjectsTemplate(isolate, global); setInitExpectation(zDevice, attributeMock); TryCatch tryCatch; v8::Local<v8::Value> result = runScript(stream.str()); if (tryCatch.HasCaught()) { String::Utf8Value value(tryCatch.Message()->Get()); } ASSERT_THAT(result.IsEmpty(), false); ASSERT_THAT(result->IsUndefined(), true); changeSignal(); result = runScript(""); result = runScript(""); ASSERT_THAT(log.empty(), false); Log::LogData logData = log.get(); ASSERT_THAT(logData.msg, StrEq("callback called")); ASSERT_THAT(log.empty(), true); }
void V8Util::openJSErrorDialog(TryCatch &tryCatch) { JNIEnv *env = JNIUtil::getJNIEnv(); if (!env) { return; } Handle<Message> message = tryCatch.Message(); jstring title = env->NewStringUTF("Runtime Error"); jstring errorMessage = TypeConverter::jsValueToJavaString(message->Get()); jstring resourceName = TypeConverter::jsValueToJavaString(message->GetScriptResourceName()); jstring sourceLine = TypeConverter::jsValueToJavaString(message->GetSourceLine()); env->CallStaticVoidMethod( JNIUtil::krollRuntimeClass, JNIUtil::krollRuntimeDispatchExceptionMethod, title, errorMessage, resourceName, message->GetLineNumber(), sourceLine, message->GetEndColumn()); env->DeleteLocalRef(title); env->DeleteLocalRef(errorMessage); env->DeleteLocalRef(resourceName); env->DeleteLocalRef(sourceLine); }
std::string V8Engine::compileScript(std::string script) { HandleScope handleScope; TryCatch tc; Local<String> source = String::New(script.c_str()); // Compile the source code. Local<Script> code = Script::Compile(source); if (!code.IsEmpty()) return ""; // There were errors, return them std::string ret = ""; Handle<Object> exception = tc.Exception()->ToObject(); String::AsciiValue exception_str(exception); ret += *exception_str; ret += "\n"; Local<Message> message = tc.Message(); ret += *(v8::String::Utf8Value( message->Get() )); ret += "\n"; ret += "Source line: "; ret += *(v8::String::Utf8Value( message->GetSourceLine() )); ret += "\n"; ret += "Source line number: "; ret += Utility::toString(message->GetLineNumber()); ret += "\n"; return ret; }
Local<String> V8EngineProxy::GetErrorMessage(TryCatch &tryCatch) { auto msg = tryCatch.Exception()->ToString(); auto stack = tryCatch.StackTrace(); bool showStackMsg = !stack.IsEmpty() && !stack->IsUndefined(); Local<String> stackStr; if (showStackMsg) { stackStr = stack->ToString(); // ... detect if the start of the stack message is the same as the exception message, then remove it (seems to happen when managed side returns an error) ... if (stackStr->Length() >= msg->Length()) { uint16_t* ss = new uint16_t[stackStr->Length() + 1]; stack->ToString()->Write(ss); auto subStackStr = NewSizedUString(ss, msg->Length()); auto stackPartStr = NewSizedUString(ss + msg->Length(), stackStr->Length() - msg->Length()); delete[] ss; if (msg->Equals(subStackStr)) stackStr = stackPartStr; } } msg = msg->Concat(msg, NewString("\r\n")); msg = msg->Concat(msg, NewString(" Line: ")); auto line = NewInteger(tryCatch.Message()->GetLineNumber())->ToString(); msg = msg->Concat(msg, line); msg = msg->Concat(msg, NewString(" Column: ")); auto col = NewInteger(tryCatch.Message()->GetStartColumn())->ToString(); msg = msg->Concat(msg, col); msg = msg->Concat(msg, NewString("\r\n")); if (showStackMsg) { msg = msg->Concat(msg, NewString(" Stack: ")); msg = msg->Concat(msg, stackStr); msg = msg->Concat(msg, NewString("\r\n")); } return msg; }
std::string GetException(TryCatch &try_catch, result_t hr) { if (try_catch.HasCaught()) { v8::String::Utf8Value exception(try_catch.Exception()); v8::Local<v8::Message> message = try_catch.Message(); if (message.IsEmpty()) return ToCString(exception); else { v8::Local<v8::Value> trace_value = try_catch.StackTrace(); if (!IsEmpty(trace_value)) { v8::String::Utf8Value stack_trace(trace_value); return ToCString(stack_trace); } std::string strError; v8::String::Utf8Value filename(message->GetScriptResourceName()); if (qstrcmp(ToCString(exception), "SyntaxError: ", 13)) { strError.append(ToCString(exception)); strError.append("\n at "); } else { strError.append((ToCString(exception) + 13)); strError.append("\n at "); } strError.append(ToCString(filename)); int lineNumber = message->GetLineNumber(); if (lineNumber > 0) { char numStr[32]; strError.append(1, ':'); sprintf(numStr, "%d", lineNumber); strError.append(numStr); strError.append(1, ':'); sprintf(numStr, "%d", message->GetStartColumn() + 1); strError.append(numStr); } return strError; } } else if (hr < 0) return getResultMessage(hr); return ""; }
void V8Util::reportException(TryCatch &tryCatch, bool showLine) { HandleScope scope; Handle<Message> message = tryCatch.Message(); if (nameSymbol.IsEmpty()) { nameSymbol = SYMBOL_LITERAL("name"); messageSymbol = SYMBOL_LITERAL("message"); } if (showLine) { Handle<Message> message = tryCatch.Message(); if (!message.IsEmpty()) { String::Utf8Value filename(message->GetScriptResourceName()); String::Utf8Value msg(message->Get()); int linenum = message->GetLineNumber(); LOGE(EXC_TAG, "Exception occurred at %s:%i: %s", *filename, linenum, *msg); } } Local<Value> stackTrace = tryCatch.StackTrace(); String::Utf8Value trace(tryCatch.StackTrace()); if (trace.length() > 0 && !stackTrace->IsUndefined()) { LOGD(EXC_TAG, *trace); } else { Local<Value> exception = tryCatch.Exception(); if (exception->IsObject()) { Handle<Object> exceptionObj = exception->ToObject(); Handle<Value> message = exceptionObj->Get(messageSymbol); Handle<Value> name = exceptionObj->Get(nameSymbol); if (!message->IsUndefined() && !name->IsUndefined()) { String::Utf8Value nameValue(name); String::Utf8Value messageValue(message); LOGE(EXC_TAG, "%s: %s", *nameValue, *messageValue); } } else { String::Utf8Value error(exception); LOGE(EXC_TAG, *error); } } }
jsvalue JsEngine::ErrorFromV8(TryCatch& trycatch) { jsvalue v; HandleScope scope; Local<Value> exception = trycatch.Exception(); v.type = JSVALUE_TYPE_UNKNOWN_ERROR; v.value.str = 0; v.length = 0; // If this is a managed exception we need to place its ID inside the jsvalue // and set the type JSVALUE_TYPE_MANAGED_ERROR to make sure the CLR side will // throw on it. if (exception->IsObject()) { Local<Object> obj = Local<Object>::Cast(exception); if (obj->InternalFieldCount() == 1) { Local<External> wrap = Local<External>::Cast(obj->GetInternalField(0)); ManagedRef* ref = (ManagedRef*)wrap->Value(); v.type = JSVALUE_TYPE_MANAGED_ERROR; v.length = ref->Id(); return v; } } jserror *error = new jserror(); memset(error, 0, sizeof(jserror)); Local<Message> message = trycatch.Message(); if (!message.IsEmpty()) { error->line = message->GetLineNumber(); error->column = message->GetStartColumn(); error->resource = AnyFromV8(message->GetScriptResourceName()); error->message = AnyFromV8(message->Get()); } if (exception->IsObject()) { Local<Object> obj2 = Local<Object>::Cast(exception); error->type = AnyFromV8(obj2->GetConstructorName()); } error->exception = AnyFromV8(exception); v.type = JSVALUE_TYPE_ERROR; v.value.ptr = error; return v; }
void DisplayExceptionLine (TryCatch &try_catch, std::string& err_msg) { // Prevent re-entry into this function. static bool displayed_error = false; if (displayed_error) return; displayed_error = true; HandleScope scope; Handle<Message> message = try_catch.Message(); fprintf(stderr, "\n"); err_msg = "JavaScript Exception\n\n"; if (!message.IsEmpty()) { // Print (filename):(line number): (message). String::Utf8Value filename(message->GetScriptResourceName()); const char* filename_string = *filename; int linenum = message->GetLineNumber(); fprintf(stderr, "%s:%i\n", filename_string, linenum); err_msg += filename_string; err_msg += ":"; char num_conv[10]; sprintf(num_conv, "%i", linenum); err_msg += num_conv; err_msg += "\n"; // Print line of source code. String::Utf8Value sourceline(message->GetSourceLine()); const char* sourceline_string = *sourceline; int start = message->GetStartColumn(); int end = message->GetEndColumn(); // fprintf(stderr, "---\nsourceline:%s\noffset:%d\nstart:%d\nend:%d\n---\n", sourceline_string, start, end); fprintf(stderr, "%s\n", sourceline_string); err_msg += sourceline_string; err_msg += "\n"; // Print wavy underline (GetUnderline is deprecated). for (int i = 0; i < start; i++) { fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr); } for (int i = start; i < end; i++) { fputc('^', stderr); } fputc('\n', stderr); err_msg += "\n"; } }
void handleException(TryCatch& tc) { Logging::log(Logging::ERROR, "V8 exception:\r\n"); HandleScope handleScope; Handle<Object> exception = tc.Exception()->ToObject(); String::AsciiValue exception_str(exception); Logging::log(Logging::ERROR, " : %s\r\n", *exception_str); /* Handle<Array> names = exception->GetPropertyNames(); for (unsigned int i = 0; i < names->Length(); i++) { std::string strI = Utility::toString((int)i); Logging::log(Logging::ERROR, " %d : %s : %s\r\n", i, *(v8::String::Utf8Value(names->Get(String::New(strI.c_str()))->ToString())), *(v8::String::Utf8Value(exception->Get(names->Get(String::New(strI.c_str()))->ToString())->ToString())) ); } */ Local<Message> message = tc.Message(); Logging::log(Logging::ERROR, "Message: Get: %s\r\n", *(v8::String::Utf8Value( message->Get() ))); Logging::log(Logging::ERROR, "Message: GetSourceLine: %s\r\n", *(v8::String::Utf8Value( message->GetSourceLine() ))); Logging::log(Logging::ERROR, "Message: GetScriptResourceName: %s\r\n", *(v8::String::Utf8Value( message->GetScriptResourceName()->ToString() ))); Logging::log(Logging::ERROR, "Message: GetLineNumber: %d\r\n", message->GetLineNumber() ); Local<Value> stackTrace = tc.StackTrace(); if (!stackTrace.IsEmpty()) { Logging::log(Logging::ERROR, "Stack trace: %s\r\n", *(v8::String::Utf8Value( stackTrace->ToString() ))); printf("\r\n\r\n^Stack trace^: %s\r\n", *(v8::String::Utf8Value( stackTrace->ToString() ))); } else Logging::log(Logging::ERROR, "No stack trace available in C++ handler (see above for possible in-script stack trace)\r\n"); #ifdef SERVER std::string clientMessage = *(v8::String::Utf8Value( message->Get() )); clientMessage += " - "; clientMessage += *(v8::String::Utf8Value( message->GetSourceLine() )); ServerSystem::fatalMessageToClients(clientMessage); #endif // assert(0); throw ScriptException("Bad!"); }
void set_perl_error(const TryCatch& try_catch) { Handle<Message> msg = try_catch.Message(); char message[1024]; snprintf( message, 1024, "%s at %s:%d", *(String::Utf8Value(try_catch.Exception())), !msg.IsEmpty() ? *(String::AsciiValue(msg->GetScriptResourceName())) : "EVAL", !msg.IsEmpty() ? msg->GetLineNumber() : 0 ); sv_setpv(ERRSV, message); sv_utf8_upgrade(ERRSV); }
TEST_F(JSZAttributeUInt24Test, setWrongValue) { int16_t expectedValue = -15; ZDevice zDevice{createZDevice()}; std::stringstream stream{}; stream << zAttributeVariable << "a.value=" << expectedValue; V8_SETUP jsZAttribute->initJsObjectsTemplate(isolate, global); setInitExpectation(zDevice, zclUInt24AttributeMock); TryCatch trycatch; v8::Local<v8::Value> result = runScript(stream.str()); ASSERT_THAT(result.IsEmpty(), true); ASSERT_THAT(trycatch.HasCaught(), true); v8::String::Utf8Value exceptionMessage(trycatch.Message()->Get()); ASSERT_THAT(*exceptionMessage, HasSubstr("Invalid parameter")); }
result_t throwSyntaxError(TryCatch &try_catch) { v8::String::Utf8Value exception(try_catch.Exception()); v8::Local<v8::Message> message = try_catch.Message(); if (message.IsEmpty()) ThrowError(ToCString(exception)); else { std::string strError; v8::String::Utf8Value filename(message->GetScriptResourceName()); if (qstrcmp(ToCString(exception), "SyntaxError: ", 13)) { strError.append(ToCString(exception)); strError.append("\n at "); } else { strError.append((ToCString(exception) + 13)); strError.append("\n at "); } strError.append(ToCString(filename)); int lineNumber = message->GetLineNumber(); if (lineNumber > 0) { char numStr[32]; strError.append(1, ':'); sprintf(numStr, "%d", lineNumber); strError.append(numStr); strError.append(1, ':'); sprintf(numStr, "%d", message->GetStartColumn() + 1); strError.append(numStr); } return Runtime::setError(strError); } return CALL_E_JAVASCRIPT; }
int ReportError(TryCatch& try_catch){ cs::String str; HandleScope handle_scope; v8::String::Value exception(try_catch.Exception()); const wchar_t* exception_string = ToCString(exception); Handle<v8::Message> message = try_catch.Message(); if (message.IsEmpty()) { str.Format(L"%s\n",exception_string); } else { cs::String buf; v8::String::Value filename(message->GetScriptResourceName()); const wchar_t* filename_string = ToCString(filename); int linenum = message->GetLineNumber(); buf.Format(L"file:\t%s\r\nline:\t%i\r\n%s\r\n\r\n", filename_string, linenum, exception_string); str += buf; v8::String::Value sourceline(message->GetSourceLine()); const wchar_t* sourceline_string = ToCString(sourceline); buf.Format(L"%s", sourceline_string); int start = message->GetStartColumn(); for (int i = 0; i < start; i++) { //str += L" "; } buf.Insert('^',start); buf.Trim(); str += buf; int end = message->GetEndColumn(); for (int i = start; i < end; i++) { //str += L"^"; } /*str += L"\n"; v8::String::Value stack_trace(try_catch.StackTrace()); if (stack_trace.length() > 0) { const wchar_t* stack_trace_string = ToCString(stack_trace); buf.Format(L"%s\n", stack_trace_string); str += buf; }*/ } return MessageBox(0,str,L"Error",MB_ICONERROR); }
static gboolean gum_script_create_context (GumScript * self, GError ** error) { GumScriptPrivate * priv = self->priv; g_assert (priv->context == NULL); { Locker locker (priv->isolate); Isolate::Scope isolate_scope (priv->isolate); HandleScope handle_scope (priv->isolate); Handle<ObjectTemplate> global_templ = ObjectTemplate::New (); _gum_script_core_init (&priv->core, self, priv->main_context, priv->isolate, global_templ); _gum_script_memory_init (&priv->memory, &priv->core, global_templ); _gum_script_process_init (&priv->process, &priv->core, global_templ); _gum_script_thread_init (&priv->thread, &priv->core, global_templ); _gum_script_module_init (&priv->module, &priv->core, global_templ); _gum_script_file_init (&priv->file, &priv->core, global_templ); _gum_script_socket_init (&priv->socket, &priv->core, global_templ); _gum_script_interceptor_init (&priv->interceptor, &priv->core, global_templ); _gum_script_stalker_init (&priv->stalker, &priv->core, global_templ); _gum_script_instruction_init (&priv->instruction, &priv->core, global_templ); Local<Context> context (Context::New (priv->isolate, NULL, global_templ)); priv->context = new GumPersistent<Context>::type (priv->isolate, context); Context::Scope context_scope (context); _gum_script_core_realize (&priv->core); _gum_script_memory_realize (&priv->memory); _gum_script_process_realize (&priv->process); _gum_script_thread_realize (&priv->thread); _gum_script_module_realize (&priv->module); _gum_script_file_realize (&priv->file); _gum_script_socket_realize (&priv->socket); _gum_script_interceptor_realize (&priv->interceptor); _gum_script_stalker_realize (&priv->stalker); _gum_script_instruction_realize (&priv->instruction); gchar * combined_source = g_strconcat ( #include "gumscript-runtime.h" "\n", priv->source, static_cast<void *> (NULL)); Local<String> source_value (String::NewFromUtf8 (priv->isolate, combined_source)); g_free (combined_source); TryCatch trycatch; Handle<Script> raw_script = Script::Compile (source_value); if (raw_script.IsEmpty ()) { Handle<Message> message = trycatch.Message (); Handle<Value> exception = trycatch.Exception (); String::Utf8Value exception_str (exception); g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Script(line %d): %s", message->GetLineNumber () - GUM_SCRIPT_RUNTIME_SOURCE_LINE_COUNT, *exception_str); } else { priv->raw_script = new GumPersistent<Script>::type (priv->isolate, raw_script); } } if (priv->raw_script == NULL) { gum_script_destroy_context (self); return FALSE; } return TRUE; }
static gboolean gum_script_create_context (GumScript * self, GError ** error) { GumScriptPrivate * priv = self->priv; g_assert (priv->context == NULL); { Handle<ObjectTemplate> global_templ = ObjectTemplate::New (); _gum_script_core_init (&priv->core, self, gum_script_emit_message, gum_script_get_scheduler (), priv->isolate, global_templ); _gum_script_memory_init (&priv->memory, &priv->core, global_templ); _gum_script_process_init (&priv->process, &priv->core, global_templ); _gum_script_thread_init (&priv->thread, &priv->core, global_templ); _gum_script_module_init (&priv->module, &priv->core, global_templ); _gum_script_file_init (&priv->file, &priv->core, global_templ); _gum_script_socket_init (&priv->socket, &priv->core, global_templ); _gum_script_interceptor_init (&priv->interceptor, &priv->core, global_templ); _gum_script_stalker_init (&priv->stalker, &priv->core, global_templ); _gum_script_symbol_init (&priv->symbol, &priv->core, global_templ); _gum_script_instruction_init (&priv->instruction, &priv->core, global_templ); Local<Context> context (Context::New (priv->isolate, NULL, global_templ)); priv->context = new GumPersistent<Context>::type (priv->isolate, context); Context::Scope context_scope (context); _gum_script_core_realize (&priv->core); _gum_script_memory_realize (&priv->memory); _gum_script_process_realize (&priv->process); _gum_script_thread_realize (&priv->thread); _gum_script_module_realize (&priv->module); _gum_script_file_realize (&priv->file); _gum_script_socket_realize (&priv->socket); _gum_script_interceptor_realize (&priv->interceptor); _gum_script_stalker_realize (&priv->stalker); _gum_script_symbol_realize (&priv->symbol); _gum_script_instruction_realize (&priv->instruction); gchar * resource_name_str = g_strconcat (priv->name, ".js", (gpointer) NULL); Local<String> resource_name (String::NewFromUtf8 (priv->isolate, resource_name_str)); ScriptOrigin origin (resource_name); g_free (resource_name_str); Local<String> source (String::NewFromUtf8 (priv->isolate, priv->source)); TryCatch trycatch; MaybeLocal<Script> maybe_code = Script::Compile (context, source, &origin); Local<Script> code; if (maybe_code.ToLocal (&code)) { priv->code = new GumPersistent<Script>::type (priv->isolate, code); } else { Handle<Message> message = trycatch.Message (); Handle<Value> exception = trycatch.Exception (); String::Utf8Value exception_str (exception); g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Script(line %d): %s", message->GetLineNumber (), *exception_str); } } if (priv->code == NULL) { gum_script_destroy_context (self); return FALSE; } return TRUE; }
int TiRootObject::executeScript(NativeObjectFactory* objectFactory, const char* javaScript, MESSAGELOOPENTRY messageLoopEntry, void* context) { HandleScope handleScope; objectFactory_ = objectFactory; globalTemplate_ = ObjectTemplate::New(); TiV8EventContainerFactory* eventFactory = TiV8EventContainerFactory::createEventContainerFactory(globalTemplate_); objectFactory->setEventContainerFactory(eventFactory); onSetGetPropertyCallback(&globalTemplate_); onSetFunctionCallback(&globalTemplate_); g_rootTemplate = ObjectTemplate::New(); context_ = Context::New(NULL, g_rootTemplate); forceSetValue(context_->Global()); context_->Global()->SetHiddenValue(String::New("globalTemplate_"), External::New(&globalTemplate_)); context_->Global()->SetHiddenValue(String::New("context_"), External::New(&context_)); setTiObjectToJsObject(context_->Global(), this); Context::Scope context_scope(context_); initializeTiObject(NULL); const char* bootstrapFilename = "bootstrap.js"; string bootstrapJavascript; { ifstream ifs((string("app/native/framework/") + bootstrapFilename).c_str()); if (!ifs) { TiLogger::getInstance().log(Ti::Msg::ERROR__Cannot_load_bootstrap_js); return -1; } getline(ifs, bootstrapJavascript, string::traits_type::to_char_type(string::traits_type::eof())); ifs.close(); } TryCatch tryCatch; Handle<Script> compiledBootstrapScript = Script::Compile(String::New(bootstrapJavascript.c_str()), String::New(bootstrapFilename)); if (compiledBootstrapScript.IsEmpty()) { String::Utf8Value error(tryCatch.Exception()); TiLogger::getInstance().log(*error); return -1; } Handle<Value> bootstrapResult = compiledBootstrapScript->Run(); if (bootstrapResult.IsEmpty()) { Local<Value> exception = tryCatch.Exception(); // FIXME: need a way to prevent double "filename + line" output Handle<Message> msg = tryCatch.Message(); stringstream ss; ss << bootstrapFilename << " line "; if (msg.IsEmpty()) { ss << "?"; } else { ss << msg->GetLineNumber(); } ss << ": " << *String::Utf8Value(exception); TiLogger::getInstance().log(ss.str().c_str()); return -1; } const char* filename = "app.js"; Handle<Script> compiledScript = Script::Compile(String::New(javaScript), String::New(filename)); if (compiledScript.IsEmpty()) { ReportException(tryCatch, true); return 1; } compiledScript->Run(); if (tryCatch.HasCaught()) { ReportException(tryCatch, true); return 1; } onStartMessagePump(); return (messageLoopEntry)(context); }