Exception Line Number in CSharpScript.EvaluateAsync

I evaluate a script using a method CSharpScript.EvaluatyAsync<T>and passing some C # code. I can easily see the number of errors per line when there is a parsing problem, for example. syntax error, but when there is an exception at runtime, all I get is AggregateExceptionwrapping my exception ( NullReferenceException) in this case, but there is no information on how to get the line number for me (3 in this example below).

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);

EDIT:

I studied this and found that the Scripting API creates an assembly without pdb information here line 127 so it will be impossible to find out where the exception occurred. I'm right?

+3
source share
2 answers

In some version of CSharpScript, the team added a solution: now you can add ScriptOptions.Default.WithEmitDebugInformation(true)to the method EvaluateAsync.

Check out my test examples below on how to extract the exception line number:

[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
source

In this case, you probably want to view the information inside the property AggregateException.InnerExceptions.

0
source

Source: https://habr.com/ru/post/1654478/


All Articles