Zie619/n8n-workflows · error · HTTPException

Error generating diagram: {str(e)}

Error message

Error generating diagram: {str(e)}

What it means

The generic 500 from GET /api/workflows/{filename}/diagram, reached only after HTTPException and JSONDecodeError branches are excluded. It means the file parsed successfully but generate_mermaid_diagram(nodes, connections) — or the surrounding code — threw while converting nodes/connections into Mermaid flowchart text. The exception is logged ('Error generating diagram for {filename}') and wrapped into the 500 detail.

Source

Thrown at api_server.py:497

            data = json.load(f)

        nodes = data.get("nodes", [])
        connections = data.get("connections", {})

        # Generate Mermaid diagram
        diagram = generate_mermaid_diagram(nodes, connections)

        return {"diagram": diagram}
    except HTTPException:
        raise
    except json.JSONDecodeError as e:
        print(f"Error parsing JSON in {filename}: {str(e)}")
        raise HTTPException(
            status_code=400, detail=f"Invalid JSON in workflow file: {str(e)}"
        )
    except Exception as e:
        print(f"Error generating diagram for {filename}: {str(e)}")
        raise HTTPException(
            status_code=500, detail=f"Error generating diagram: {str(e)}"
        )


def generate_mermaid_diagram(nodes: List[Dict], connections: Dict) -> str:
    """Generate Mermaid.js flowchart code from workflow nodes and connections."""
    if not nodes:
        return "graph TD\n  EmptyWorkflow[No nodes found in workflow]"

    # Create mapping for node names to ensure valid mermaid IDs
    mermaid_ids = {}
    for i, node in enumerate(nodes):
        node_id = f"node{i}"
        node_name = node.get("name", f"Node {i}")
        mermaid_ids[node_name] = node_id

    # Start building the mermaid diagram
    mermaid_code = ["graph TD"]

View on GitHub (pinned to 94007c1445)

Solutions

  1. Read the detail text — it carries the exact exception from generate_mermaid_diagram (e.g. KeyError: 'name').
  2. Inspect the workflow JSON's nodes/connections arrays for the shape the generator expects (list of dicts with name/type; connections keyed by node name).
  3. Make generate_mermaid_diagram defensive: use node.get('name', f'node_{i}') and skip malformed entries instead of throwing.
  4. As a stopgap, view the raw workflow JSON via the detail endpoint while the diagram bug is fixed.

Example fix

# before
for i, node in enumerate(nodes):
    mermaid_ids[node['name']] = f'N{i}'

# after (tolerate missing/odd fields)
for i, node in enumerate(nodes):
    name = node.get('name') or f'node_{i}'
    mermaid_ids[name] = f'N{i}'
Defensive patterns

Strategy: try-catch

Validate before calling

def has_expected_shape(path):
    import json
    data = json.load(open(path, encoding='utf-8'))
    nodes = data.get('nodes', [])
    conns = data.get('connections', {})
    return (
        isinstance(nodes, list)
        and all(isinstance(n, dict) for n in nodes)
        and isinstance(conns, dict)
        and all(isinstance(k, str) for k in conns)
    )

Try / catch

try:
    d = client.get(f'/api/workflows/{name}/diagram').json()['diagram']
except HTTPError as e:
    if e.response.status_code == 500:
        d = 'graph TD\n  Error[Diagram generation failed — see raw JSON view]'

Prevention

When it happens

Trigger: A workflow whose node objects lack the fields generate_mermaid_diagram() assumes (missing 'name'/'type'), connection keys referencing nonexistent nodes, non-string node names breaking Mermaid ID mapping, or unexpected node shapes (n8n version differences) tripping the ID-sanitization logic.

Common situations: Indexing workflows exported by a newer/older n8n with extra nesting; workflows containing sticky notes or special nodes with unusual schemas; node names with quotes/unicode that escape the ID mapping.

Related errors


AI-assisted analysis of Zie619/n8n-workflows@94007c1445 (2026-08-15). Data as JSON: /api/errors/d28adf41f65a38d5. Report an issue: GitHub.