1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
5 using System
.Diagnostics
;
6 using System
.Diagnostics
.CodeAnalysis
;
8 namespace System
.Runtime
.ExceptionServices
10 // This class defines support for separating the exception dispatch details
11 // (like stack trace, watson buckets, etc) from the actual managed exception
12 // object. This allows us to track error (via the exception object) independent
13 // of the path the error takes.
15 // This is particularly useful for frameworks that wish to propagate
16 // exceptions (i.e. errors to be precise) across threads.
17 public sealed class ExceptionDispatchInfo
19 private readonly Exception _exception
;
20 private readonly Exception
.DispatchState _dispatchState
;
22 private ExceptionDispatchInfo(Exception exception
)
24 _exception
= exception
;
25 _dispatchState
= exception
.CaptureDispatchState();
28 // This static method is used to create an instance of ExceptionDispatchInfo for
29 // the specified exception object and save all the required details that maybe
30 // needed to be propagated when the exception is "rethrown" on a different thread.
31 public static ExceptionDispatchInfo
Capture(Exception source
)
35 throw new ArgumentNullException(nameof(source
));
38 return new ExceptionDispatchInfo(source
);
41 // Return the exception object represented by this ExceptionDispatchInfo instance
42 public Exception SourceException
=> _exception
;
44 // When a framework needs to "Rethrow" an exception on a thread different (but not necessarily so) from
45 // where it was thrown, it should invoke this method against the ExceptionDispatchInfo
46 // created for the exception in question.
48 // This method will restore the original stack trace and bucketing details before throwing
49 // the exception so that it is easy, from debugging standpoint, to understand what really went wrong on
50 // the original thread.
55 // Restore the exception dispatch details before throwing the exception.
56 _exception
.RestoreDispatchState(_dispatchState
);
60 // Throws the source exception, maintaining the original bucketing details and augmenting
61 // rather than replacing the original stack trace.
63 public static void Throw(Exception source
) => Capture(source
).Throw();