spectreconsole/spectre.console · error · InvalidOperationException

Invalid hex color '#{hex}'. {ex.Message}

Error message

Invalid hex color '#{hex}'. {ex.Message}

What it means

ParseHexColor caught an exception while converting the hex digits (e.g. non-hex characters causing Convert.ToUInt32 to throw). The original exception message is appended, e.g. for `[#ZZZZZZ]`. Note the re-thrown message says '#{hex}' but the '#' was stripped internally, so the printed token lacks its leading '#'.

Source

Thrown at src/Spectre.Console.Ansi/AnsiMarkupTagParser.cs:10

namespace Spectre.Console;

internal static class AnsiMarkupTagParser
{
    public static (Style Style, Link? Link) Parse(string text)
    {
        var result = Parse(text, out var error);
        if (error != null)
        {
            throw new InvalidOperationException(error);
        }

        return result ?? throw new InvalidOperationException("Could not parse style.");
    }

    public static bool TryParse(string text, [NotNullWhen(true)] out (Style Style, Link?)? result)
    {
        result = Parse(text, out _);
        return result != null;
    }

    private static (Style Style, Link? Link)? Parse(string text, out string? error)
    {
        var effectiveDecoration = (Decoration?)null;
        var effectiveForeground = (Color?)null;
        var effectiveBackground = (Color?)null;
        var effectiveLink = (string?)null;

View on GitHub (pinned to 0acc92fada)

Solutions

  1. Use only characters 0-9 and A-F/a-f in the hex portion
  2. Validate with a regex like ^#[0-9A-Fa-f]{6}$ before building the tag
  3. Fall back to a named color or rgb() form

Example fix

// before
AnsiMarkup.Parse("[#GGGGGG]text[/]");

// after
AnsiMarkup.Parse("[#00FFAA]text[/]");
Defensive patterns

Strategy: validation

Validate before calling

public static bool IsValidHex(string token) =>
    Regex.IsMatch(token, @"^#[0-9A-Fa-f]{6}$") || Regex.IsMatch(token, @"^#[0-9A-Fa-f]{3}$");

Try / catch

try { AnsiMarkup.Parse(markup); }
catch (InvalidOperationException ex) when (ex.Message.StartsWith("Invalid hex color"))
{ /* replace with a known-good hex value */ }

Prevention

When it happens

Trigger: A `#`-prefixed part containing non-hexadecimal characters, e.g. `[#GGGGGG]`, `[#12GH56]`, or a hex value with an embedded space.

Common situations: Programmatic color generation that produces invalid hex digits; user-typed color with a typo; locale/encoding issues inserting odd characters.

Related errors


AI-assisted analysis of spectreconsole/spectre.console@0acc92fada (2026-08-13). Data as JSON: /api/errors/5c1a0e5a1af0b942. Report an issue: GitHub.