Zie619/n8n-workflows · error · HTTPException

Error fetching categories: {str(e)}

Error message

Error fetching categories: {str(e)}

What it means

A generic 500 from /api/categories. The handler tries to load context/unique_categories.json, falls back to building a set from db data (defaulting entries without a 'category' key to 'Uncategorized'), and finally to a hardcoded list. The except still fires when the JSON file exists but is unreadable/corrupt AND the DB fallback path raises, or when any other unexpected error occurs in the chain.

Source

Thrown at api_server.py:661

                with open(search_categories_file, "r", encoding="utf-8") as f:
                    search_data = json.load(f)

                unique_categories = set()
                for item in search_data:
                    if item.get("category"):
                        unique_categories.add(item["category"])
                    else:
                        unique_categories.add("Uncategorized")

                categories = sorted(list(unique_categories))
                return {"categories": categories}
            else:
                # Last resort: return basic categories
                return {"categories": ["Uncategorized"]}

    except Exception as e:
        print(f"Error loading categories: {e}")
        raise HTTPException(
            status_code=500, detail=f"Error fetching categories: {str(e)}"
        )


@app.get("/api/category-mappings")
async def get_category_mappings():
    """Get filename to category mappings for client-side filtering."""
    try:
        search_categories_file = Path("context/search_categories.json")
        if not search_categories_file.exists():
            return {"mappings": {}}

        with open(search_categories_file, "r", encoding="utf-8") as f:
            search_data = json.load(f)

        # Convert to a simple filename -> category mapping
        mappings = {}
        for item in search_data:

View on GitHub (pinned to 94007c1445)

Solutions

  1. Regenerate context/unique_categories.json (re-run the category generation script or the reindex pipeline) so it holds valid JSON.
  2. Validate the file manually: python -c "import json;json.load(open('context/unique_categories.json'))" to confirm it parses.
  3. Check the printed server log line 'Error loading categories:' — it contains the underlying exception.
  4. Ensure the process cwd contains the context/ directory, or convert the relative Path to an absolute configured path.
Defensive patterns

Strategy: fallback

Validate before calling

import json
from pathlib import Path

def categories_file_ok(path: str = "context/unique_categories.json") -> bool:
    p = Path(path)
    if not p.exists():
        return False
    try:
        json.loads(p.read_text(encoding="utf-8"))
        return True
    except (json.JSONDecodeError, OSError):
        return False

Try / catch

try:
    cats = client.get("/api/categories").json()["categories"]
except HTTPError as e:
    if e.response.status_code == 500:
        cats = ["Uncategorized"]  # mirror the server's own last-resort fallback
    else:
        raise

Prevention

When it happens

Trigger: GET /api/categories when context/unique_categories.json exists but contains invalid JSON (truncated generation), when the file lacks read permission, or when the fallback DB query raises (missing table) after the file check fails.

Common situations: The context file was partially written by a generator script that was interrupted; the server runs under a different user without read permission on context/; a schema change made the DB fallback query reference a column that no longer exists.

Related errors


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