When embedding the V8 Javascript engine in a C++ project, I haven't found any way to get the line number for compilation failure of a script. I have tried the following:
//Given that v8 is initialized, isolate, context and script_source is setup.
v8::TryCatch try_catch{isolate};
//Compile the script from source
v8::Local<v8::Script> script;
if (!v8::Script::Compile(context, script_source).ToLocal(&script)) {
//Compilation failed
//Print exception from TryCatch
auto exc = try_catch.Exception();
v8::String::Utf8Value err{isolate, exc};
if (*err) {
std::cerr << "Exception: " << *err << std::endl;
}
//Print StackTrace from TryCatch
v8::Local<v8::Value> trace;
if (try_catch.StackTrace(context).ToLocal(&trace)) {
v8::String::Utf8Value trace_str{isolate, trace};
std::cerr << "Trace: " << *trace_str << std::endl;
}
//Print stack trace from isolate
auto stack = v8::StackTrace::CurrentStackTrace(isolate, 100);
std::cerr << "Stack trace:\n";
for (int i = 0; i < stack->GetFrameCount(); ++i) {
auto frame = stack->GetFrame(isolate, i);
v8::String::Utf8Value function_name{isolate, frame->GetFunctionName()};
std::cerr
<< "\tat "
<< function_name
<< " (line " << frame->GetLineNumber()
<< ", column " << frame->GetColumn() << ")\n";
}
}
The exception retrieved with v8::TryCatch::Exception when converted to a string results in error messages like this:
SyntaxError: missing ) after argument list
No line number or column in the message. I get the exact same message when using the v8::TryCatch::StackTrace converted to a string, still no line number.
The stack trace returned by v8::StackTrace::CurrentStackTrace doesn't contain any frames, so I can't get the line number or column there either.
I also tried adding a v8::ScriptOrigin to the v8::Script::Compilefunction, but that did not affect the error message.