Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Created December 23, 2023 16:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save karenpayneoregon/410190b79d9ada2b9836df1b9deb2377 to your computer and use it in GitHub Desktop.
Save karenpayneoregon/410190b79d9ada2b9836df1b9deb2377 to your computer and use it in GitHub Desktop.
Using Spectre.Console NuGet package to colorize runtime exceptions
/// <summary>
/// Custom setting for presenting runtime exceptions using AnsiConsole.WriteException.
///
/// The idea here is to present different types of exceptions with different colors while
/// one would be for all exceptions and the other(s) for specific exception types.
/// </summary>
public class ExceptionHelpers
{
/// <summary>
/// Provides colorful exception messages in cyan and fuchsia
/// </summary>
/// <param name="exception"><see cref="Exception"/></param>
public static void ColorWithCyanFuchsia(Exception exception)
{
AnsiConsole.WriteException(exception, new ExceptionSettings
{
Format = ExceptionFormats.ShortenEverything | ExceptionFormats.ShowLinks,
Style = new ExceptionStyle
{
Exception = new Style().Foreground(Color.Grey),
Message = new Style().Foreground(Color.DarkSeaGreen),
NonEmphasized = new Style().Foreground(Color.Cornsilk1),
Parenthesis = new Style().Foreground(Color.Cornsilk1),
Method = new Style().Foreground(Color.Fuchsia),
ParameterName = new Style().Foreground(Color.Cornsilk1),
ParameterType = new Style().Foreground(Color.Aqua),
Path = new Style().Foreground(Color.Red),
LineNumber = new Style().Foreground(Color.Cornsilk1),
}
});
}
/// <summary>
/// Provides a colorful exception message
/// </summary>
/// <param name="exception"><see cref="Exception"/></param>
public static void ColorStandard(Exception exception)
{
AnsiConsole.WriteException(exception, new ExceptionSettings
{
Format = ExceptionFormats.ShortenEverything | ExceptionFormats.ShowLinks,
Style = new ExceptionStyle
{
Exception = new Style().Foreground(Color.Grey),
Message = new Style().Foreground(Color.White),
NonEmphasized = new Style().Foreground(Color.Cornsilk1),
Parenthesis = new Style().Foreground(Color.GreenYellow),
Method = new Style().Foreground(Color.DarkOrange),
ParameterName = new Style().Foreground(Color.Cornsilk1),
ParameterType = new Style().Foreground(Color.Aqua),
Path = new Style().Foreground(Color.White),
LineNumber = new Style().Foreground(Color.Cornsilk1),
}
});
}
}
internal partial class Program
{
static void Main(string[] args)
{
try
{
var json = File.ReadAllText("C:\\temp\\Dummy.json");
}
catch (Exception e)
{
ExceptionHelpers.ColorStandard(e);
}
Console.ReadLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment