我正在构建一个引擎,该引擎使用 Jint 来执行带有一系列函数的 javascript 文件。
问题是如果有
你从 Jint 得到的只是一个 JavaScriptException,没有关于错误发生位置的上下文。
现在我被降级为添加日志语句只是为了在脚本中找到问题。
如果任何 Error() 的抛出伴随着用 js 函数的堆栈跟踪填充的 stack 属性,那将是非常有帮助的。
我遇到了同样的问题,其中一些长脚本非常难以调试。 我们所做的是将Engine.Execute
包裹在我们自己的try
块中,并使用Engine.GetLastSyntaxNode().Location.Start
值重新抛出。 例子:
c#
var engine = new Engine();
try
{
engine.Execute("some code that throws...");
}
catch(JavaScriptException exc)
{
var location = engine.GetLastSyntaxNode().Location.Start;
throw new ApplicationException(
String.Format("{0} (Line {1}, Column {2})",
exc.Error,
location.Line,
location.Column
), exc);
}
请注意,如果location
对象是JavaScriptException
对象的_always_ 部分会好得多。
谢谢,这是非常有帮助的。
我仍然认为有一个可用的堆栈跟踪是非常有价值的。 原因是(在我的情况下)脚本是动态组装的,因此从行号到动态脚本中的实际行需要一些额外的工作。
对于一些解析错误,我还遇到了Esprima.ParserException
异常。
而且我发现添加导致错误的行的文本很有用(如在 ClearScript 异常中打印)
public void Run(string script)
{
JintEngine.Execute(script);
catch (Esprima.ParserException ex)
{
throw new ApplicationException($"{ex.Error} (Line {ex.LineNumber}, Column {ex.Column}), -> {ReadLine(script, ex.LineNumber)})", ex);
}
catch (Jint.Runtime.JavaScriptException ex)
{
throw new ApplicationException($"{ex.Error} (Line {ex.LineNumber}, Column {ex.Column}), -> {ReadLine(script, ex.LineNumber)})", ex);
}
}
private static string ReadLine(string text, int lineNumber)
{
using var reader = new System.IO.StringReader(text);
string line;
int currentLineNumber = 0;
do
{
currentLineNumber += 1;
line = reader.ReadLine();
}
while (line != null && currentLineNumber < lineNumber);
return (currentLineNumber == lineNumber) ? line : string.Empty;
}
最有用的评论
我遇到了同样的问题,其中一些长脚本非常难以调试。 我们所做的是将
Engine.Execute
包裹在我们自己的try
块中,并使用Engine.GetLastSyntaxNode().Location.Start
值重新抛出。 例子:c# var engine = new Engine(); try { engine.Execute("some code that throws..."); } catch(JavaScriptException exc) { var location = engine.GetLastSyntaxNode().Location.Start; throw new ApplicationException( String.Format("{0} (Line {1}, Column {2})", exc.Error, location.Line, location.Column ), exc); }
请注意,如果
location
对象是JavaScriptException
对象的_always_ 部分会好得多。