feat(backend): error codes, backend i18n (en/el) and language fields
Platform v2 step 1.2 (APPS_PLATFORM D-12, §3.2, §8).
- core/errors.py: XeniaError + CODES registry; handlers give every error the
{"error": {code, params, message}, "detail"} shape: XeniaError, wrapped
HTTPException (http.<status>, detail untouched), validation.invalid (FastAPI
detail list kept), and internal.error 500 with the request id (body, header
and log line)
- orders: the 18 "Order not found" raises -> XeniaError("order.not_found")
- core/i18n: t(key, lang, **params) with en/el JSON (en fallback), venue/zone/
user language resolution, normalize_language; 56 print keys
- printer_service: every printed label goes through keys. Kitchen,
cancellation and service-item tickets print in the prep zone's language
(-> venue.language); reports/receipts/synopsis in venue.language. Greek
output is unchanged. Print retries now pass the job's zone (language and
item grouping were lost on retries)
- users.language, prep_zones.language (revision 0003), setting venue.language
(default en); editable via PATCH /auth/me, staff update, prep zones API;
"" = inherit
- tests: error shapes, key/placeholder parity, fallback, kitchen ticket per
zone/venue language, language APIs; pack rule CS-12
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
"""API errors as stable codes (APPS_PLATFORM D-12, §3.2).
|
||||
|
||||
Every error response has this shape:
|
||||
{"error": {"code": "order.not_found", "params": {"order_id": 7}, "message": "Order 7 not found."},
|
||||
"detail": "Order 7 not found."}
|
||||
- code: stable identifier; frontends translate it (i18n key `errors.<code>`).
|
||||
- params: values the translated text can use.
|
||||
- message: English, for logs, curl and un-migrated screens.
|
||||
- detail: kept for frontends written before v2 (they read `detail`).
|
||||
|
||||
New and converted code raises XeniaError:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
The status comes from the registry below; pass status= only to override it.
|
||||
Plain HTTPException (still in most v1 routers; converted gradually, plan step 6.x)
|
||||
is wrapped as code "http.<status>" with its original `detail` untouched.
|
||||
Request validation errors become "validation.invalid" with the field errors in params.
|
||||
Unhandled exceptions become "internal.error" (500) with the request id in params.
|
||||
|
||||
Agent notes:
|
||||
- Add every new code to CODES with its HTTP status and English message (str.format
|
||||
placeholders from params). tests/test_errors.py fails on a raised code that
|
||||
isn't registered (via XeniaError's constructor).
|
||||
- Codes are part of the API contract: never rename one; add a new one instead.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from http import HTTPStatus
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
logger = logging.getLogger("xenia.errors")
|
||||
|
||||
# code -> (HTTP status, English message)
|
||||
CODES: dict[str, tuple[int, str]] = {
|
||||
# access / licensing / modules (filled in by steps 1.3-1.9)
|
||||
"access.denied": (403, "You don't have permission to do this ({key})."),
|
||||
"access.override_possible": (403, "A manager can approve this ({key})."),
|
||||
"module.disabled": (403, "The {module} module is turned off."),
|
||||
"module.not_licensed": (402, "This site's license doesn't include {module}."),
|
||||
"license.limit_reached": (402, "License limit reached for {limit} ({max})."),
|
||||
"license.expired": (402, "The license has expired."),
|
||||
# identity
|
||||
"auth.invalid_credentials": (401, "Wrong username or password."),
|
||||
"auth.session_ended": (401, "Your session has ended. Please log in again."),
|
||||
"device.revoked": (401, "This device was removed. Pair it again."),
|
||||
"device.not_paired": (401, "This device isn't paired with the venue."),
|
||||
# validation
|
||||
"validation.invalid": (422, "Some fields are invalid."),
|
||||
"validation.unknown_language": (422, "Unsupported language: {language}."),
|
||||
"validation.unknown_timezone": (422, "Unknown time zone: {timezone}."),
|
||||
# server
|
||||
"internal.error": (500, "Something went wrong on the server (request {request_id})."),
|
||||
# domain
|
||||
"order.not_found": (404, "Order {order_id} not found."),
|
||||
}
|
||||
|
||||
|
||||
class XeniaError(Exception):
|
||||
"""An API error with a registered code. raise XeniaError("order.not_found", order_id=5)."""
|
||||
|
||||
def __init__(self, code: str, status: int | None = None, **params):
|
||||
if code not in CODES:
|
||||
raise KeyError(f"unregistered error code {code!r}: add it to core/errors.py CODES")
|
||||
default_status, template = CODES[code]
|
||||
self.code = code
|
||||
self.status = status or default_status
|
||||
self.params = params
|
||||
try:
|
||||
self.message = template.format(**params)
|
||||
except (KeyError, IndexError):
|
||||
self.message = template
|
||||
super().__init__(self.message)
|
||||
|
||||
|
||||
def error_body(code: str, message: str, params: dict | None = None, detail=None) -> dict:
|
||||
return {"error": {"code": code, "params": params or {}, "message": message},
|
||||
"detail": message if detail is None else detail}
|
||||
|
||||
|
||||
async def _xenia_error_handler(request: Request, exc: XeniaError):
|
||||
return JSONResponse(error_body(exc.code, exc.message, exc.params), status_code=exc.status)
|
||||
|
||||
|
||||
async def _http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
detail = exc.detail
|
||||
if isinstance(detail, str):
|
||||
message = detail
|
||||
elif isinstance(detail, dict) and isinstance(detail.get("message"), str):
|
||||
message = detail["message"]
|
||||
else:
|
||||
try:
|
||||
message = HTTPStatus(exc.status_code).phrase
|
||||
except ValueError:
|
||||
message = "Error"
|
||||
return JSONResponse(error_body(f"http.{exc.status_code}", message, detail=detail),
|
||||
status_code=exc.status_code, headers=getattr(exc, "headers", None))
|
||||
|
||||
|
||||
async def _validation_handler(request: Request, exc: RequestValidationError):
|
||||
errors = [{"field": ".".join(str(p) for p in e.get("loc", ())[1:]) or None,
|
||||
"type": e.get("type"), "message": e.get("msg")} for e in exc.errors()]
|
||||
# `detail` stays FastAPI's usual list, so existing frontends keep working
|
||||
return JSONResponse(error_body("validation.invalid", CODES["validation.invalid"][1],
|
||||
{"errors": jsonable_encoder(errors)}, detail=jsonable_encoder(exc.errors())),
|
||||
status_code=422)
|
||||
|
||||
|
||||
async def _unhandled_handler(request: Request, exc: Exception):
|
||||
"""Last resort: a bug. Logged with the traceback; the client gets the request id
|
||||
(also in the X-Request-ID header) so support can find the log lines."""
|
||||
from core.logging import current_request_id
|
||||
rid = getattr(request.state, "request_id", None) or current_request_id() or "-"
|
||||
logger.exception("http.unhandled_error request_id=%s path=%s", rid, request.url.path)
|
||||
err = XeniaError("internal.error", request_id=rid)
|
||||
return JSONResponse(error_body(err.code, err.message, err.params), status_code=500,
|
||||
headers={"X-Request-ID": rid})
|
||||
|
||||
|
||||
def install_error_handlers(app: FastAPI) -> None:
|
||||
app.add_exception_handler(Exception, _unhandled_handler)
|
||||
app.add_exception_handler(XeniaError, _xenia_error_handler)
|
||||
app.add_exception_handler(StarletteHTTPException, _http_exception_handler)
|
||||
app.add_exception_handler(RequestValidationError, _validation_handler)
|
||||
Reference in New Issue
Block a user