Skip to content

[BUG]: Exception handlers registered but never attached to the FastAPI app #82

@GaneshPatil7517

Description

@GaneshPatil7517

⚡️ Describe the Bug

The custom exception handler for AppError is defined in handlers.py via the register_exception_handlers(app) function, but this function is never called anywhere in the application. In main.py, the FastAPI app is created and routers are included, but the exception handlers are never attached:

# api/main.py (current)
from fastapi import FastAPI
from api.routes import templates, forms

app = FastAPI()

app.include_router(templates.router)
app.include_router(forms.router)
# ❌ register_exception_handlers(app) is never called

This means when AppError is raised (e.g., in forms.py line 15 when a template is not found), FastAPI does not know how to handle it and returns a generic 500 Internal Server Error instead of the intended structured JSON error response.

# api/routes/forms.py — this raise will result in a 500, not a 404
if not get_template(db, form.template_id):
    raise AppError("Template not found", status_code=404)

👣 Steps to Reproduce

  1. Clone the repo and install dependencies (pip install -r requirements.txt)
  2. Initialize the database: python -m api.db.init_db
  3. Start the API server: uvicorn api.main:app --reload
  4. Send a POST request to /forms/fill with a non-existent template_id:
curl -X POST http://localhost:8000/forms/fill \
  -H "Content-Type: application/json" \
  -d '{"template_id": 9999, "input_text": "test"}'
  1. Observe a 500 Internal Server Error instead of a 404 JSON response.

📉 Expected Behavior

The API should return a clean JSON error response with the correct status code:

{
  "error": "Template not found"
}

with HTTP status 404, as designed in handlers.py

🖥️ Environment Information

OS: Windows 11 / Ubuntu 22.04 (reproducible on any OS)
Python: 3.11+ (also tested on 3.13)
Docker/Compose Version: N/A (reproducible without Docker)
Ollama Model used: N/A (bug is in API layer, not LLM)

📸 Screenshots/Logs

Server log output when hitting the endpoint with an invalid template ID:
INFO: 127.0.0.1:xxxxx - "POST /forms/fill HTTP/1.1" 500 Internal Server Error

The traceback shows an unhandled AppError exception because no handler is registered.

🕵️ Possible Fix

Import and call register_exception_handlers(app) in main.py:

from fastapi import FastAPI
from api.routes import templates, forms
from api.errors.handlers import register_exception_handlers

app = FastAPI()

register_exception_handlers(app)

app.include_router(templates.router)
app.include_router(forms.router)

Metadata

Metadata

Labels

No labels
No labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions