Three-pane webmail client. - Backend: FastAPI + async SQLAlchemy + arq worker (Postgres/Redis), IMAP/SMTP sync, threading, search, drafts/outbox with undo, attachments, 2FA. - Frontend: React 18 + Vite + TypeScript + TanStack Query + Tailwind; three-pane UI with rich-text composer, light/dark themes, resizable panels. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
36 lines
1.4 KiB
Python
36 lines
1.4 KiB
Python
"""Consistent API error shape ``{error:{code,message}}`` (SPEC §9.1)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import NoReturn
|
|
|
|
from fastapi import FastAPI, HTTPException, Request
|
|
from fastapi.responses import JSONResponse
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
|
|
def api_error(status_code: int, code: str, message: str) -> HTTPException:
|
|
"""Build an :class:`HTTPException` carrying the ``{code,message}`` detail."""
|
|
return HTTPException(status_code=status_code, detail={"code": code, "message": message})
|
|
|
|
|
|
def raise_api_error(status_code: int, code: str, message: str) -> NoReturn:
|
|
"""Raise :func:`api_error` (typed as ``NoReturn`` for control-flow clarity)."""
|
|
raise api_error(status_code, code, message)
|
|
|
|
|
|
async def _handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
|
|
detail = exc.detail
|
|
if isinstance(detail, dict) and "code" in detail:
|
|
body = {"error": detail}
|
|
else:
|
|
body = {"error": {"code": "http_error", "message": str(detail)}}
|
|
headers = getattr(exc, "headers", None)
|
|
return JSONResponse(status_code=exc.status_code, content=body, headers=headers)
|
|
|
|
|
|
def register_error_handlers(app: FastAPI) -> None:
|
|
"""Install the error-shape handler for all HTTP exceptions."""
|
|
app.add_exception_handler(StarletteHTTPException, _handler) # type: ignore[arg-type]
|
|
app.add_exception_handler(HTTPException, _handler) # type: ignore[arg-type]
|