Skip to content

Instantly share code, notes, and snippets.

@voroninp
Created December 15, 2022 11:01
Show Gist options
  • Save voroninp/1dda9337b6f33218b884bd91af6e8051 to your computer and use it in GitHub Desktop.
Save voroninp/1dda9337b6f33218b884bd91af6e8051 to your computer and use it in GitHub Desktop.
Augment exception with id of current activity.
using System.Diagnostics;
using System.Runtime.ExceptionServices;
namespace Helpers;
public static class ExceptionHelper
{
private const string ActivityIdKey = "ActivityId";
private static readonly object Sync = new();
private static readonly EventHandler<FirstChanceExceptionEventArgs> AugmentingWithCurrentActivityIdExceptionHandler = (_, e) =>
{
if (Activity.Current is Activity activity && !e.Exception.Data.Contains(ActivityIdKey))
{
e.Exception.Data[ActivityIdKey] = activity.Id;
}
};
private static volatile bool _augmentingExceptionsWithCurrentActivityId;
/// <summary>
/// Tries to add to exceptions' <see cref="Exception.Data">data</see> dictionary an id
/// of <see cref="Activity.Current">current</see> <see cref="Activity">activity</see>,
/// if any. This can be convenient to correlate logged exceptions with traces.
/// </summary>
public static void AugmentExceptionsWithCurrentActivityId()
{
if (_augmentingExceptionsWithCurrentActivityId)
{
return;
}
lock (Sync)
{
if (_augmentingExceptionsWithCurrentActivityId)
{
return;
}
_augmentingExceptionsWithCurrentActivityId = true;
AppDomain.CurrentDomain.FirstChanceException += AugmentingWithCurrentActivityIdExceptionHandler;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment