Skip to content

Commit

Permalink
Capture original exception stacktrace in ThrowMeaningfulException (#965)
Browse files Browse the repository at this point in the history
* Capture original exception stacktrace in ThrowMeaningfulException

Co-authored-by: Casey Zhang <[email protected]>
  • Loading branch information
caseyzhang123 and cazha123 authored Sep 23, 2021
1 parent c51d984 commit 95da84a
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
22 changes: 22 additions & 0 deletions Jint.Tests/Runtime/ErrorTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Esprima;
using Jint.Runtime;
using Jint.Tests.Runtime.TestClasses;
using System;
using System.Collections.Generic;
using Xunit;
Expand Down Expand Up @@ -282,6 +283,20 @@ at getItem (items, itemIndex) get-item.js:2:22
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")]
Expand All @@ -303,5 +318,12 @@ private static void EqualIgnoringNewLineDifferences(string expected, string actu
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 changes: 11 additions & 0 deletions Jint.Tests/Runtime/TestClasses/HelloWorld.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Jint.Tests.Runtime.TestClasses
{
public class HelloWorld
{
public void ThrowException()
{
int zero = 0;
int x = 5 / zero;
}
}
}
3 changes: 2 additions & 1 deletion Jint/Runtime/ExceptionHelper.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -141,7 +142,7 @@ public static void ThrowMeaningfulException(Engine engine, TargetInvocationExcep
ThrowError(engine, meaningfulException.Message);
}

throw meaningfulException;
ExceptionDispatchInfo.Capture(meaningfulException).Throw();
}

[DoesNotReturn]
Expand Down

0 comments on commit 95da84a

Please sign in to comment.