spectreconsole/spectre.console · error · InvalidOperationException

Invalid RGB color '{rgb}'.

Error message

Invalid RGB color '{rgb}'.

What it means

ParseRgbColor finished without throwing but the shape was wrong: fewer than 3 characters after 'rgb', missing or mismatched parentheses, or not exactly 3 comma-separated parts. Reports 'Invalid RGB color {rgb}.'

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 the exact form rgb(r,g,b) with parentheses and three comma-separated integers
  2. Validate the string shape before embedding in markup
  3. Prefer #rrggbb for programmatically generated colors to avoid formatting pitfalls

Example fix

// before
AnsiMarkup.Parse("[rgb(1 2 3)]text[/]");

// after
AnsiMarkup.Parse("[rgb(1,2,3)]text[/]");
Defensive patterns

Strategy: validation

Validate before calling

public static bool IsWellFormedRgb(string token) =>
    Regex.IsMatch(token, @"^rgb\(\d{1,3},\d{1,3},\d{1,3}\)$");

Try / catch

try { AnsiMarkup.Parse(markup); }
catch (InvalidOperationException ex) when (ex.Message.StartsWith("Invalid RGB color"))
{ /* rewrite using exactly rgb(r,g,b) */ }

Prevention

When it happens

Trigger: Malformed rgb syntax: `[rgb(1,2)]` (2 parts), `[rgb(1,2,3,4)]` (4 parts), `[rgb1,2,3]` (no parens), `[rgb]` (too short), or `[rgb(1 2 3)]` (space-separated).

Common situations: Missing parentheses; space vs comma confusion; extra trailing comma producing an empty part handled by StringSplitOptions.RemoveEmptyEntries changing the count.

Related errors


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