spectreconsole/spectre.console · error · InvalidOperationException
Color number must be less than or equal to 255 (was {number}
Error message
Color number must be less than or equal to 255 (was {number}) What it means
A tag part parses as an integer but exceeds 255, the maximum 256-color palette index. The value is reported in the message.
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
- Clamp indices to 0-255 with Math.Clamp
- Use `#rrggbb` or `rgb(r,g,b)` syntax for arbitrary true-color values instead of a palette index
- Validate the range before constructing the tag
Example fix
// before
AnsiMarkup.Parse($"[{value}]x[/]"); // value can be 300
// after
if (value is >= 0 and <= 255)
AnsiMarkup.Parse($"[{value}]x[/]");
else
AnsiMarkup.Parse($"[#{value:X6}]x[/]"); // or use true-color hex Defensive patterns
Strategy: validation
Validate before calling
int safeIndex = Math.Clamp(rawIndex, 0, 255);
var markup = rawIndex is >= 0 and <= 255 ? $"[{rawIndex}]text[/]" : $"[#{rawIndex:X6}]text[/]"; Try / catch
try { AnsiMarkup.Parse(markup); }
catch (InvalidOperationException ex) when (ex.Message.Contains("Color number must be less than or equal to 255"))
{ /* switch to true-color hex form instead of palette index */ } Prevention
- Treat palette indices as strictly 0-255
- Use #rrggbb for values outside the palette range
- Clamp or branch on numeric inputs before formatting markup
When it happens
Trigger: Markup like `[256]`, `[1000]`, or code that interpolates an out-of-range integer into a tag, e.g. `$"[{i}]"` where i > 255.
Common situations: Looping over an unbounded range and using the counter as a color index; misreading the palette as 0-999; feeding an RGB component as a palette index.
Related errors
- Color number must be greater than or equal to 0 (was {number
- Could not find color '{part}'.
- Could not find color or style '{part}'.
- A foreground color has already been set.
- A background color has already been set.
AI-assisted analysis of spectreconsole/spectre.console@0acc92fada (2026-08-13).
Data as JSON: /api/errors/f164dbda1d1c17c9.
Report an issue: GitHub.