Skip to content

Commit

Permalink
Capture stacktrace of exceptions thrown from async (#524)
Browse files Browse the repository at this point in the history
* Capture stacktrace of exceptions thrown from async

* tidy
  • Loading branch information
robertcoltheart authored Jun 23, 2024
1 parent 9cc2900 commit 1981464
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ public class when_running_async_specifications_with_exceptions : RunnerSpecs

It should_have_failures = () =>
results.Should().Match(x => x.All(y => !y.Passed));

It should_have_exception_details = () =>
results.Should().Match(x => x.All(r => r.Exception.TypeName == nameof(InvalidOperationException) &&
r.Exception.Message == "something went wrong" &&
r.Exception.StackTrace.Contains(typeof(AsyncSpecificationsWithExceptions).FullName)));
}

#if NETCOREAPP
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#if !NET35
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;

Expand All @@ -13,7 +14,11 @@ internal class AsyncSynchronizationContext : SynchronizationContext

private int callCount;

#if !NET40
private ExceptionDispatchInfo exception;
#else
private Exception exception;
#endif

public AsyncSynchronizationContext(SynchronizationContext inner)
{
Expand All @@ -28,7 +33,11 @@ private void Execute(SendOrPostCallback callback, object state)
}
catch (Exception ex)
{
#if !NET40
exception = ExceptionDispatchInfo.Capture(ex);
#else
exception = ex;
#endif
}
finally
{
Expand Down Expand Up @@ -89,11 +98,19 @@ public override void Send(SendOrPostCallback d, object state)
}
catch (Exception ex)
{
#if !NET40
exception = ExceptionDispatchInfo.Capture(ex);
#else
exception = ex;
#endif
}
}

#if !NET40
public ExceptionDispatchInfo WaitAsync()
#else
public Exception WaitAsync()
#endif
{
events.Wait();

Expand Down
4 changes: 4 additions & 0 deletions src/Machine.Specifications/Runner/Impl/DelegateRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@ public void Execute()

if (exception != null)
{
#if !NET40
exception.Throw();
#else
throw exception;
#endif
}
}
finally
Expand Down

0 comments on commit 1981464

Please sign in to comment.