RickStrahl / Westwind.Scripting

Small C# library to provide dynamic runtime code compilation from source code for code and expressions execution

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ThrowExceptions throws both compilation and runtime errors

BrettJaner opened this issue · comments

Hey Rick,

I wanted to bring something to your attention that seemed a bit off based on the documentation. When I set the ThrowsException flag to true on the CSharpScriptExecution instance, I'm seeing exceptions thrown for both compile time and runtime errors. The documentation seems to contradict this saying that the ThrowsException flag should only effect runtime errors. Here's a test that I wouldn't expect to pass, but does:

[TestMethod]
public void CompileInvalidClassDefinition()
{
    var code = @"
        using System;

        namespace Testing.Test
        {
            public class Test
            {
                public void Foo();
            }
        }";

    var script = new CSharpScriptExecution()
    {
        ThrowExceptions = true
    };

    script.AddDefaultReferencesAndNamespaces();

    Assert.ThrowsException<ApplicationException>(() => script.CompileClass(code));
}

My apologies if I missed something, and this ends up just being noise.

-Brett

Took a look and yes you're right - lib has SetError() to set errors and uses the ThrowsExceptions property to determine.

Fix:

  • Add an additional parameter for bool noExceptions = false
  • CompileClass sets this parm to true so no error is thrown
  • Added your test and changed to check for compilation error
        [TestMethod]
        public void CompileInvalidClassDefinitionShouldNotThrow()
        {
            var code = @"
        using System;

        namespace Testing.Test
        {
            public class Test
            {
                public void Foo();
            }
        }";

            var script = new CSharpScriptExecution() { ThrowExceptions = true };

            script.AddDefaultReferencesAndNamespaces();

            dynamic result = script.CompileClass(code);

            // Should have an error
            Assert.IsTrue(script.Error, script.ErrorMessage);
        }

Thank you for the quick fix!