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

+3 -1
View File
@@ -26,7 +26,9 @@ async function callAdmin(method, path, body) {
const headers = { 'Content-Type': 'application/json', 'X-Admin-Token': adminToken };
const res = await fetch(path, { method, headers, body: body ? JSON.stringify(body) : undefined });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || res.statusText);
// detail is a bare string on the admin endpoints, but the shared dependencies
// (auth) answer with the structured {code, message} form of app/api/errors.py.
if (!res.ok) throw new Error(data.detail?.message || data.detail || res.statusText);
return data;
}
+24 -1
View File
@@ -51,10 +51,33 @@ async function call(method, path, body) {
clearTimeout(timeoutId);
}
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || res.statusText);
if (!res.ok) throw new Error(apiErrorMessage(data.detail) || res.statusText);
return data;
}
// The API is single-language by design: it answers with a stable machine code
// plus an English message (app/api/errors.py), and picking the words is the
// client's job. Unknown code (older/newer server, an endpoint not converted
// yet) → show the English message rather than nothing.
function apiErrorMessage(detail) {
if (!detail) return null;
if (typeof detail === 'string') return detail; // endpoints still returning a bare string
return tOrNull('error.' + detail.code, errorParams(detail.params)) || detail.message || null;
}
// Amounts cross the wire in sats (`*_sats`); every translated string wants PLM,
// so expose both and let each language's phrasing pick. Done generically here
// so a new *_sats param needs no client change.
function errorParams(params) {
const out = { ...(params || {}) };
for (const [key, value] of Object.entries(params || {})) {
if (key.endsWith('_sats') && typeof value === 'number') {
out[key.slice(0, -5) + '_plm'] = value / SATS_PER_PLM;
}
}
return out;
}
function switchTab(name) {
document.getElementById('tab-login').classList.toggle('active', name === 'login');
document.getElementById('tab-register').classList.toggle('active', name === 'register');
+109
View File
@@ -113,6 +113,23 @@ const TRANSLATIONS = {
'toast.roundWon': 'You won round #{id}! +{amount} PLM',
'toast.withdrawSent': 'Withdrawal sent.',
// Keyed by the `code` the API returns in its structured error detail
// (app/api/errors.py). A code with no entry here falls back to the API's
// own English `message`, so a new server-side error is never a blank toast.
'error.network_unavailable': 'Not connected to the network, please try again shortly.',
'error.no_round_open': 'No round is open right now, please try again shortly.',
'error.round_closing': 'The current round is closing, please try again shortly.',
'error.already_betting': 'You already have an active bet in the current round.',
'error.insufficient_balance': 'Insufficient balance.',
'error.amount_below_network_fee': 'The amount is too small to cover the network fee.',
'error.amount_below_minimum': 'The minimum withdrawal amount is {minimum_plm} PLM.',
'error.current_password_incorrect': 'The current password is incorrect.',
'error.password_too_short': 'The new password must be at least {minimum} characters.',
'error.username_taken': 'This username is already taken.',
'error.invalid_credentials': 'Wrong username or password.',
'error.derivation_index_conflict': 'Registration failed, please try again.',
'error.session_expired': 'Session expired, please log in again.',
'loading.creating': 'Creating…',
'loading.loggingIn': 'Logging in…',
'loading.sendingBet': 'Placing bet…',
@@ -228,6 +245,20 @@ const TRANSLATIONS = {
'toast.roundWon': 'Hai vinto il round #{id}! +{amount} PLM',
'toast.withdrawSent': 'Withdrawal inviato.',
'error.network_unavailable': 'Nessuna connessione alla rete, riprova tra poco.',
'error.no_round_open': 'Nessun round aperto in questo momento, riprova tra poco.',
'error.round_closing': 'Il round corrente si sta chiudendo, riprova tra poco.',
'error.already_betting': 'Hai già una bet attiva nel round corrente.',
'error.insufficient_balance': 'Saldo insufficiente.',
'error.amount_below_network_fee': "L'importo è troppo basso per coprire la fee di rete.",
'error.amount_below_minimum': "L'importo minimo di prelievo è {minimum_plm} PLM.",
'error.current_password_incorrect': 'La password attuale non è corretta.',
'error.password_too_short': 'La nuova password deve avere almeno {minimum} caratteri.',
'error.username_taken': 'Questo username è già stato preso.',
'error.invalid_credentials': 'Username o password errati.',
'error.derivation_index_conflict': 'Registrazione non riuscita, riprova.',
'error.session_expired': 'Sessione scaduta, accedi di nuovo.',
'loading.creating': 'Creazione…',
'loading.loggingIn': 'Accesso…',
'loading.sendingBet': 'Invio bet…',
@@ -343,6 +374,20 @@ const TRANSLATIONS = {
'toast.roundWon': '¡Has ganado la ronda #{id}! +{amount} PLM',
'toast.withdrawSent': 'Retiro enviado.',
'error.network_unavailable': 'Sin conexión con la red, inténtalo de nuevo en un momento.',
'error.no_round_open': 'No hay ninguna ronda abierta ahora mismo, inténtalo de nuevo en un momento.',
'error.round_closing': 'La ronda actual se está cerrando, inténtalo de nuevo en un momento.',
'error.already_betting': 'Ya tienes una apuesta activa en la ronda actual.',
'error.insufficient_balance': 'Saldo insuficiente.',
'error.amount_below_network_fee': 'El importe es demasiado pequeño para cubrir la comisión de red.',
'error.amount_below_minimum': 'El importe mínimo de retiro es {minimum_plm} PLM.',
'error.current_password_incorrect': 'La contraseña actual no es correcta.',
'error.password_too_short': 'La nueva contraseña debe tener al menos {minimum} caracteres.',
'error.username_taken': 'Este nombre de usuario ya está en uso.',
'error.invalid_credentials': 'Usuario o contraseña incorrectos.',
'error.derivation_index_conflict': 'No se pudo completar el registro, inténtalo de nuevo.',
'error.session_expired': 'Sesión caducada, vuelve a iniciar sesión.',
'loading.creating': 'Creando…',
'loading.loggingIn': 'Entrando…',
'loading.sendingBet': 'Enviando apuesta…',
@@ -458,6 +503,20 @@ const TRANSLATIONS = {
'toast.roundWon': 'Vous avez gagné le round #{id} ! +{amount} PLM',
'toast.withdrawSent': 'Retrait envoyé.',
'error.network_unavailable': 'Pas de connexion au réseau, réessayez dans un instant.',
'error.no_round_open': "Aucun round n'est ouvert pour le moment, réessayez dans un instant.",
'error.round_closing': 'Le round en cours est en train de se fermer, réessayez dans un instant.',
'error.already_betting': 'Vous avez déjà une mise active dans le round en cours.',
'error.insufficient_balance': 'Solde insuffisant.',
'error.amount_below_network_fee': 'Le montant est trop faible pour couvrir les frais de réseau.',
'error.amount_below_minimum': 'Le montant minimum de retrait est de {minimum_plm} PLM.',
'error.current_password_incorrect': "Le mot de passe actuel n'est pas correct.",
'error.password_too_short': 'Le nouveau mot de passe doit comporter au moins {minimum} caractères.',
'error.username_taken': "Ce nom d'utilisateur est déjà pris.",
'error.invalid_credentials': "Nom d'utilisateur ou mot de passe incorrect.",
'error.derivation_index_conflict': "L'inscription a échoué, veuillez réessayer.",
'error.session_expired': 'Session expirée, veuillez vous reconnecter.',
'loading.creating': 'Création…',
'loading.loggingIn': 'Connexion…',
'loading.sendingBet': 'Envoi de la mise…',
@@ -573,6 +632,20 @@ const TRANSLATIONS = {
'toast.roundWon': 'Du hast Runde #{id} gewonnen! +{amount} PLM',
'toast.withdrawSent': 'Auszahlung gesendet.',
'error.network_unavailable': 'Keine Verbindung zum Netzwerk, bitte versuche es gleich erneut.',
'error.no_round_open': 'Derzeit ist keine Runde offen, bitte versuche es gleich erneut.',
'error.round_closing': 'Die laufende Runde wird gerade geschlossen, bitte versuche es gleich erneut.',
'error.already_betting': 'Du hast bereits eine aktive Wette in der laufenden Runde.',
'error.insufficient_balance': 'Nicht genügend Guthaben.',
'error.amount_below_network_fee': 'Der Betrag ist zu klein, um die Netzwerkgebühr zu decken.',
'error.amount_below_minimum': 'Der Mindestauszahlungsbetrag beträgt {minimum_plm} PLM.',
'error.current_password_incorrect': 'Das aktuelle Passwort ist nicht korrekt.',
'error.password_too_short': 'Das neue Passwort muss mindestens {minimum} Zeichen lang sein.',
'error.username_taken': 'Dieser Benutzername ist bereits vergeben.',
'error.invalid_credentials': 'Benutzername oder Passwort falsch.',
'error.derivation_index_conflict': 'Registrierung fehlgeschlagen, bitte erneut versuchen.',
'error.session_expired': 'Sitzung abgelaufen, bitte melde dich erneut an.',
'loading.creating': 'Wird erstellt…',
'loading.loggingIn': 'Anmeldung…',
'loading.sendingBet': 'Wette wird gesendet…',
@@ -688,6 +761,20 @@ const TRANSLATIONS = {
'toast.roundWon': 'Вы выиграли раунд #{id}! +{amount} PLM',
'toast.withdrawSent': 'Вывод средств отправлен.',
'error.network_unavailable': 'Нет соединения с сетью, повторите попытку чуть позже.',
'error.no_round_open': 'Сейчас нет открытого раунда, повторите попытку чуть позже.',
'error.round_closing': 'Текущий раунд закрывается, повторите попытку чуть позже.',
'error.already_betting': 'У вас уже есть активная ставка в текущем раунде.',
'error.insufficient_balance': 'Недостаточно средств.',
'error.amount_below_network_fee': 'Сумма слишком мала, чтобы покрыть комиссию сети.',
'error.amount_below_minimum': 'Минимальная сумма вывода — {minimum_plm} PLM.',
'error.current_password_incorrect': 'Текущий пароль указан неверно.',
'error.password_too_short': 'Новый пароль должен содержать не менее {minimum} символов.',
'error.username_taken': 'Это имя пользователя уже занято.',
'error.invalid_credentials': 'Неверное имя пользователя или пароль.',
'error.derivation_index_conflict': 'Не удалось завершить регистрацию, попробуйте ещё раз.',
'error.session_expired': 'Сессия истекла, войдите снова.',
'loading.creating': 'Создание…',
'loading.loggingIn': 'Вход…',
'loading.sendingBet': 'Отправка ставки…',
@@ -803,6 +890,20 @@ const TRANSLATIONS = {
'toast.roundWon': '你赢得了第 {id} 回合!+{amount} PLM',
'toast.withdrawSent': '提现已发送。',
'error.network_unavailable': '未连接到网络,请稍后重试。',
'error.no_round_open': '当前没有开放的回合,请稍后重试。',
'error.round_closing': '当前回合正在结束,请稍后重试。',
'error.already_betting': '你在当前回合已有一笔有效下注。',
'error.insufficient_balance': '余额不足。',
'error.amount_below_network_fee': '金额太小,不足以支付网络手续费。',
'error.amount_below_minimum': '最低提现金额为 {minimum_plm} PLM。',
'error.current_password_incorrect': '当前密码不正确。',
'error.password_too_short': '新密码长度至少需要 {minimum} 个字符。',
'error.username_taken': '该用户名已被占用。',
'error.invalid_credentials': '用户名或密码错误。',
'error.derivation_index_conflict': '注册失败,请重试。',
'error.session_expired': '会话已过期,请重新登录。',
'loading.creating': '正在创建…',
'loading.loggingIn': '正在登录…',
'loading.sendingBet': '正在下注…',
@@ -832,6 +933,14 @@ function t(key, params) {
return interpolate(dict[key] ?? TRANSLATIONS.en[key] ?? key, params);
}
// Like t(), but returns null instead of echoing the key back when nothing is
// defined for it — lets a caller fall back to a string of its own (e.g. the
// API's English message for an error code this build doesn't know yet).
function tOrNull(key, params) {
const str = TRANSLATIONS[currentLang]?.[key] ?? TRANSLATIONS.en[key];
return str === undefined ? null : interpolate(str, params);
}
function currentDateLocale() {
return DATE_LOCALES[currentLang] || 'en-US';
}