spectreconsole/spectre.console · error · InvalidOperationException

Could not parse style.

Error message

Could not parse style.

What it means

Defensive fallback in the public AnsiMarkupTagParser.Parse: the private Parse returned null but produced no error string, so the message 'Could not parse style.' is thrown. In the current implementation every null return path sets an error, so this branch is effectively unreachable.

Source

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

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;

        var parts = text.Split([' ']);
        var foreground = true;
        foreach (var part in parts)

View on GitHub (pinned to 0acc92fada)

Solutions

  1. Report it as a library bug with the offending tag text and stack trace
  2. Catch InvalidOperationException when rendering dynamic markup so a parse failure degrades gracefully
  3. Use AnsiMarkupTagParser.TryParse (which returns bool) if you need non-throwing behavior
Defensive patterns

Strategy: try-catch

Validate before calling

// Use the non-throwing TryParse where available:
if (AnsiMarkupTagParser.TryParse(tag, out var parsed)) { /* use parsed */ }

Try / catch

try { var style = AnsiMarkupTagParser.Parse(tag); }
catch (InvalidOperationException ex) when (ex.Message == "Could not parse style.")
{ /* defensive/unreachable: report upstream, fall back to Style.Plain */ }

Prevention

When it happens

Trigger: Not reproducible via the public API with current code: all failure paths populate the error string before returning null. It exists as a safety net against a future code path that returns null without setting error.

Common situations: Should never surface to a consumer. If seen, it indicates an internal regression where a Parse branch returns null without an error message.

Related errors


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