我正在使用CSharpScript.EvaluatyAsync<T>方法评估一个脚本,并传递一些C#代码。当存在解析问题(例如语法错误)时,我可以很容易地看到错误的行数,但是当存在运行时异常时,我得到的只是一个包装我的异常(NullReferenceException)的NullReferenceException,但对于如何为我获得行号(在下面的示例中为3)没有任何线索。
Console.WriteLine(CSharpScript.EvaluateAsync<int>(
@"string s = null;
// some comment at line 2
var upper = s.ToUpper(); // Null reference exception at line 3
// more code").Result);编辑:
我一直在研究这个问题,并发现Scripting创建了一个没有pdb信息的这里第127行程序集,所以这不可能知道异常发生在哪里。我说的对吗?
发布于 2017-10-12 14:35:30
在CSharpScript的某些版本中,团队添加了一个解决方案:现在可以将ScriptOptions.Default.WithEmitDebugInformation(true)添加到EvaluateAsync方法中。
关于如何提取异常行号,请参阅下面的测试用例:
[TestMethod]
public void LineNumberInStackTrace()
{
try
{
var result = CSharpScript.EvaluateAsync<int>(
@"string s = null;
// some comment at line 2
var upper = s.ToUpper(); // Null reference exception at line 3
// more code", ScriptOptions.Default.WithEmitDebugInformation(true)).Result;
}
catch (AggregateException e)
{
if (e.InnerException is NullReferenceException inner)
{
var startIndex = inner.StackTrace.IndexOf(":line ", StringComparison.Ordinal) + 6;
var lineNumberStr = inner.StackTrace.Substring(
startIndex, inner.StackTrace.IndexOf("\r", StringComparison.Ordinal) - startIndex);
var lineNumber = Int32.Parse(lineNumberStr);
Assert.AreEqual(3, lineNumber);
return;
}
}
Assert.Fail();
}
[TestMethod]
public void LineNumberNotInStackTrace()
{
try
{
var result = CSharpScript.EvaluateAsync<int>(
@"string s = null;
// some comment at line 2
var upper = s.ToUpper(); // Null reference exception at line 3
// more code").Result;
}
catch (AggregateException e)
{
if (e.InnerException is NullReferenceException inner)
{
var startIndex = inner.StackTrace.IndexOf(":line ", StringComparison.Ordinal);
Assert.AreEqual(-1, startIndex);
return;
}
}
Assert.Fail();
}https://stackoverflow.com/questions/37125385
复制相似问题