Browse Source

Capture original exception stacktrace in ThrowMeaningfulException (#965)

* Capture original exception stacktrace in ThrowMeaningfulException

Co-authored-by: Casey Zhang <[email protected]>
caseyzhang123 3 years ago
parent
commit
95da84a5aa

+ 22 - 0
Jint.Tests/Runtime/ErrorTests.cs

@@ -1,5 +1,6 @@
 using Esprima;
 using Jint.Runtime;
+using Jint.Tests.Runtime.TestClasses;
 using System;
 using System.Collections.Generic;
 using Xunit;
@@ -282,6 +283,20 @@ var x = b(7);";
             EqualIgnoringNewLineDifferences(expected, ex.ToString());
         }
 
+        [Fact]
+        public void StackTraceIsForOriginalException()
+        {
+            var engine = new Engine();
+            engine.SetValue("HelloWorld", new HelloWorld());
+            const string script = @"HelloWorld.ThrowException();";
+
+            var ex = Assert.Throws<DivideByZeroException>(() => engine.Execute(script));
+
+            const string expected = "HelloWorld";
+
+            ContainsIgnoringNewLineDifferences(expected, ex.ToString());
+        }
+
         [Theory]
         [InlineData("Error")]
         [InlineData("EvalError")]
@@ -303,5 +318,12 @@ var x = b(7);";
             actual = actual.Replace("\r\n", "\n");
             Assert.Equal(expected, actual);
         }
+
+        private static void ContainsIgnoringNewLineDifferences(string expectedSubstring, string actualString)
+        {
+            expectedSubstring = expectedSubstring.Replace("\r\n", "\n");
+            actualString = actualString.Replace("\r\n", "\n");
+            Assert.Contains(expectedSubstring, actualString);
+        }
     }
 }

+ 11 - 0
Jint.Tests/Runtime/TestClasses/HelloWorld.cs

@@ -0,0 +1,11 @@
+namespace Jint.Tests.Runtime.TestClasses
+{
+    public class HelloWorld
+    {
+        public void ThrowException()
+        {
+            int zero = 0;
+            int x = 5 / zero;
+        }
+    }
+}

+ 2 - 1
Jint/Runtime/ExceptionHelper.cs

@@ -1,6 +1,7 @@
 using System;
 using System.Diagnostics.CodeAnalysis;
 using System.Reflection;
+using System.Runtime.ExceptionServices;
 using Jint.Native;
 using Jint.Runtime.CallStack;
 using Jint.Runtime.References;
@@ -141,7 +142,7 @@ namespace Jint.Runtime
                 ThrowError(engine, meaningfulException.Message);
             }
 
-            throw meaningfulException;
+            ExceptionDispatchInfo.Capture(meaningfulException).Throw();
         }
 
         [DoesNotReturn]