"""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.`). - 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." 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})."), "access.override_invalid": (403, "This approval isn't valid any more. Ask a manager again."), "access.not_overridable": (422, "{key} can't be approved by a manager."), "access.approver_lacks_key": (403, "That account can't approve this ({key})."), "access.override_rate_limited": (429, "Too many wrong PINs. Wait a few minutes and try again."), "access.unknown_key": (422, "There is no permission {key}."), "access.cannot_grant": (403, "You can only give permissions you have yourself ({key})."), "module.disabled": (403, "The {module} module is turned off."), "module.not_licensed": (402, "This site's license doesn't include {module}."), "module.unknown": (404, "There is no module {module}."), "module.cannot_disable": (400, "{module} is part of the core and can't be turned off."), "license.limit_reached": (402, "License limit reached for {module} {limit} ({max})."), "license.expired": (402, "The license has expired."), "license.history_limited": (402, "This license shows only the last {days} days of history ({module})."), # identity "auth.invalid_credentials": (401, "Wrong username or password."), "auth.session_ended": (401, "Your session has ended. Please log in again."), "auth.session_exists": (409, "You're already logged in on another {client}. Log out there first."), "auth.login_mode_not_allowed": (403, "This way of logging in isn't enabled ({mode})."), "auth.mode_needs_device": (403, "Logging in by {mode} only works on a paired device."), "auth.username_required": (422, "Enter your username."), "auth.client_not_allowed": (403, "This account can't use the {client} app."), "auth.session_not_found": (404, "Session not found."), "auth.wrong_pin": (401, "Wrong PIN. {attempts_left} tries left before you are signed out."), "auth.support_not_configured": (503, "Support access isn't set up on this site."), "auth.support_code_invalid": (401, "That support code is wrong or has expired. Ask for a new challenge."), "auth.support_rate_limited": (429, "Too many support challenges. Wait a few minutes and try again."), "pos.shift_required": (409, "Start your shift before selling."), "pos.payment_invalid": (422, "This payment doesn't add up ({reason})."), "pos.fiscal_vat_missing": (422, "Fiscal receipts are on, but these products have no VAT group: {names}."), "pos.line_invalid": (422, "Cart line {line} can't be sold as chosen ({reason})."), "pos.table_not_found": (404, "Table {table_id} not found."), "pos.table_not_yours": (403, "{table} isn't in your zones. A manager can add the zone to your account."), "pos.items_changed": (409, "Some of these items were paid or cancelled in the meantime. Check the order and try again."), "pos.order_unpaid": (409, "Items still unpaid: {count}. Take the payment or cancel them first."), "refund.invalid": (422, "This refund doesn't add up ({reason})."), "refund.too_old": (409, "Only payments from today's business day can be refunded at the counter."), "refund.items_changed": (409, "Some of these items were refunded in the meantime. Check the order and try again."), "online.not_found": (404, "Online order {order_id} not found."), "online.status_changed": (409, "This online order was changed on another screen in the meantime. Check where it is now."), "kds.item_not_found": (404, "Item {item_id} not found on this order."), "kds.item_claimed": (409, "{name} is already on this item."), "kds.claim_needs_staff": (403, "Only a staff member can claim an item."), "device.revoked": (401, "This device was removed. Pair it again."), "device.not_paired": (401, "This device isn't paired with the venue."), "device.out_of_scope": (403, "A {app} device can't do this ({key})."), "device.required": (401, "This login belongs to a paired device. Use it from that device."), "device.not_found": (404, "Device {device_id} not found."), "device.pair_code_invalid": (404, "That pairing code is wrong or has expired."), "device.pair_rate_limited": (429, "Too many pairing requests. Wait a few minutes and try again."), "device.not_an_app": (422, "{app} is not an app that runs on a device."), "device.login_mode_invalid": (422, "A {app} device can't use the login mode {mode}."), "device.link_invalid": (422, "Device {device_id} can't be linked to this device."), # validation "validation.invalid": (422, "Some fields are invalid."), "validation.unknown_language": (422, "Unsupported language: {language}."), "validation.unknown_timezone": (422, "Unknown time zone: {timezone}."), "validation.setting_value": (422, "{key} can't be set to {value!r}."), "validation.device_config": (422, "This device setting is not valid: {key}."), # server "internal.error": (500, "Something went wrong on the server (request {request_id})."), # domain "order.not_found": (404, "Order {order_id} not found."), "notification.not_found": (404, "Notification {notification_id} not found."), "system.log_not_found": (404, "There is no log file for {date}."), "catalog.unknown_category": (422, "There is no category {category_id}."), "catalog.primary_not_listed": (422, "The main category ({category_id}) must be one of the product's categories."), } 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)