首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CSharpScript.EvaluateAsync中的异常行号

CSharpScript.EvaluateAsync中的异常行号
EN

Stack Overflow用户
提问于 2016-05-09 21:01:19
回答 1查看 1.6K关注 0票数 3

我正在使用CSharpScript.EvaluatyAsync<T>方法评估一个脚本,并传递一些C#代码。当存在解析问题(例如语法错误)时,我可以很容易地看到错误的行数,但是当存在运行时异常时,我得到的只是一个包装我的异常(NullReferenceException)的NullReferenceException,但对于如何为我获得行号(在下面的示例中为3)没有任何线索。

代码语言:javascript
复制
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行程序集,所以这不可能知道异常发生在哪里。我说的对吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-12 14:35:30

在CSharpScript的某些版本中,团队添加了一个解决方案:现在可以将ScriptOptions.Default.WithEmitDebugInformation(true)添加到EvaluateAsync方法中。

关于如何提取异常行号,请参阅下面的测试用例:

代码语言:javascript
复制
[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();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37125385

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档