Answer user-facing API failures with a machine-readable error code

The dashboard now speaks seven languages but every failure path still showed
the API's raw English text ("insufficient balance", "current password is
incorrect"), which is the most frequent and least forgiving part of the UI to
leave untranslated.

Rather than teach the API about locales, it keeps answering in one language
and hands the client something to translate: `detail` becomes
{code, message, params}, where message stays English for non-dashboard
consumers (curl, tests) and code maps onto `error.<code>` in i18n.js. An
unknown code falls back to message, so a client older or newer than the server
degrades to English instead of a blank toast.

Domain exceptions (BetError, WithdrawalError) subclass the new ApiError and
carry the code from where the failure actually happens; str(exc) is still the
English message, so existing tests keep matching on it. Interpolated values
travel in params rather than baked into the English sentence — amounts as
*_sats, from which the frontend derives a *_plm sibling, so each language can
place them wherever its grammar wants.

admin.js reads detail.message defensively: the admin endpoints still return a
bare string, but the shared auth dependencies now return the structured form.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Opus 5 committed 2026-07-26 21:44:39 +02:00
1 parent 7048fe7ea6
commit 0cf35147ad
13 files changed
+254 -31

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
"""Machine-readable error codes for user-facing API failures.
The dashboard is multilingual (app/static/i18n.js) but the API is not: every
message produced here stays English. What travels alongside it is a stable
`code` the client maps onto its own translated string (`error.<code>`), falling
back to `message` for any code it doesn't recognize — so a non-dashboard
consumer (curl, tests, a future client) still gets something readable without
having to know the code table.
`detail` is therefore an object rather than the FastAPI-default bare string:
{"code": "insufficient_balance", "message": "insufficient balance", "params": {}}
`params` carries the values interpolated into the message (amounts, limits) so
the translated string can place them wherever its own grammar needs them,
instead of the client having to parse them back out of the English text.
"""
from typing import Any
from fastapi import HTTPException
class ApiError(Exception):
"""Domain-layer error carrying the code the client will translate.
Subclassed per domain (BetError, WithdrawalError) so services keep raising
their own exception type. `str(exc)` is still the plain English message.
"""
def __init__(self, code: str, message: str, **params: Any) -> None:
super().__init__(message)
self.code = code
self.message = message
self.params = params
def as_detail(self) -> dict[str, Any]:
return {"code": self.code, "message": self.message, "params": self.params}
def http_error(status_code: int, code: str, message: str, **params: Any) -> HTTPException:
"""HTTPException whose detail is the structured object described above."""
return HTTPException(status_code, ApiError(code, message, **params).as_detail())
def from_api_error(status_code: int, exc: ApiError) -> HTTPException:
return HTTPException(status_code, exc.as_detail())
+8 -3
View File
@@ -1,7 +1,8 @@
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi import APIRouter, Depends, Request, status
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.errors import from_api_error, http_error
from app.auth.dependencies import get_current_user
from app.bets.service import BetError, place_bet
from app.db.models import User
@@ -25,13 +26,17 @@ async def create_bet(
) -> BetResponse:
listener = request.app.state.electrum_listener
if listener.client is None:
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, "not connected to the network, try again shortly")
raise http_error(
status.HTTP_503_SERVICE_UNAVAILABLE,
"network_unavailable",
"not connected to the network, try again shortly",
)
async with request.app.state.user_locks.acquire(user.id):
try:
participant = await place_bet(session, listener.client, user)
except BetError as exc:
raise HTTPException(status.HTTP_400_BAD_REQUEST, str(exc)) from exc
raise from_api_error(status.HTTP_400_BAD_REQUEST, exc) from exc
return BetResponse(
round_id=participant.round_id,
+11 -3
View File
@@ -1,8 +1,9 @@
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi import APIRouter, Depends, status
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.errors import http_error
from app.auth.dependencies import get_current_user
from app.auth.security import hash_password, verify_password
from app.db.models import Round, RoundParticipant, User
@@ -56,9 +57,16 @@ async def change_password(
admin-only /admin/users/{id}/reset-password (which is for a user who's
actually locked out and can't provide it)."""
if not verify_password(body.current_password, user.password_hash):
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "current password is incorrect")
raise http_error(
status.HTTP_401_UNAUTHORIZED, "current_password_incorrect", "current password is incorrect"
)
if len(body.new_password) < _MIN_PASSWORD_LENGTH:
raise HTTPException(status.HTTP_400_BAD_REQUEST, f"new password must be at least {_MIN_PASSWORD_LENGTH} characters")
raise http_error(
status.HTTP_400_BAD_REQUEST,
"password_too_short",
f"new password must be at least {_MIN_PASSWORD_LENGTH} characters",
minimum=_MIN_PASSWORD_LENGTH,
)
user.password_hash = hash_password(body.new_password)
await session.commit()
+8 -3
View File
@@ -1,7 +1,8 @@
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi import APIRouter, Depends, Request, status
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.errors import from_api_error, http_error
from app.auth.dependencies import get_current_user
from app.db.models import User
from app.db.session import get_session
@@ -31,7 +32,11 @@ async def create_withdrawal(
) -> WithdrawalResponse:
listener = request.app.state.electrum_listener
if listener.client is None:
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, "not connected to the network, try again shortly")
raise http_error(
status.HTTP_503_SERVICE_UNAVAILABLE,
"network_unavailable",
"not connected to the network, try again shortly",
)
async with request.app.state.user_locks.acquire(user.id):
try:
@@ -39,7 +44,7 @@ async def create_withdrawal(
session, listener.client, user, body.external_address, body.amount_sats
)
except WithdrawalError as exc:
raise HTTPException(status.HTTP_400_BAD_REQUEST, str(exc)) from exc
raise from_api_error(status.HTTP_400_BAD_REQUEST, exc) from exc
return WithdrawalResponse(
txid=withdrawal.txid,