Jint: 请添加从错误和异常中获取堆栈跟踪的能力

创建于 2014-11-12  ·  3评论  ·  资料来源: sebastienros/jint

我正在构建一个引擎,该引擎使用 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_ 部分会好得多。

所有3条评论

我遇到了同样的问题,其中一些长脚本非常难以调试。 我们所做的是将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;
}
此页面是否有帮助?
0 / 5 - 0 等级

相关问题

sebastienros picture sebastienros  ·  34评论

lahma picture lahma  ·  15评论

ciel picture ciel  ·  13评论

Jugolo picture Jugolo  ·  13评论

appel1 picture appel1  ·  25评论