fix(query): preserve structured backend errors

This commit is contained in:
miracle authored and GitHub committed 2026-08-02 16:37:46 +08:00
1 parent 2e9dcdc26b
commit bcafc4a474
58 files changed
+4182 -554

No files matched your search

+84
View File
@@ -2,6 +2,7 @@ import { readFileSync } from "node:fs";
import { describe, expect, it as test } from "vitest";
import { createI18n } from "vue-i18n";
import { translateBackendError, type BackendErrorTranslate } from "@/i18n/backend-errors";
import { BackendErrorException, normalizeBackendError } from "@/lib/backend/errorUtils";
import en from "@/i18n/locales/en";
import es from "@/i18n/locales/es";
import it from "@/i18n/locales/it";
@@ -24,6 +25,21 @@ const LOCALES = {
type LocaleKey = keyof typeof LOCALES;
const STRUCTURED_BACKEND_ERROR_KEYS = [
"backendErrors.jdbc.connectionFailed",
"backendErrors.jdbc.connectionInterrupted",
"backendErrors.jdbc.operationTimedOut",
"backendErrors.jdbc.operationCanceled",
"backendErrors.jdbc.busyRetryLater",
"backendErrors.jdbc.runtimeReplaced",
"backendErrors.jdbc.sqlFailed",
"backendErrors.jdbc.protocolFailed",
"backendErrors.jdbc.contractInvalid",
"backendErrors.jdbc.legacyFailure",
"backendErrors.legacy",
"backendErrors.unknown",
] as const;
// Reproduces the exact string crates/dbx-core/src/agent_service.rs builds on
// Windows: `\` line continuations strip the newline plus the following indent.
const WINDOWS_JRE_REMOVE_ERROR = [
@@ -125,6 +141,12 @@ describe("backend error translation", () => {
// alongside the other non-English locales.
const localeKeys = Object.keys(LOCALES) as LocaleKey[];
test.each(localeKeys)("all structured catalog keys exist in %s", (locale) => {
for (const key of STRUCTURED_BACKEND_ERROR_KEYS) {
expect(lookup(LOCALES[locale] as unknown as Record<string, unknown>, key), `${locale}:${key}`).toEqual(expect.any(String));
}
});
describe.each(localeKeys)("in %s", (locale) => {
const t = translatorFor(locale);
@@ -157,6 +179,68 @@ describe("backend error translation", () => {
expect(translateBackendError(t, new Error(message))).toBe(expected);
expect(translateBackendError(t, { message })).toBe(expected);
});
test("preserves and translates structured BackendError envelopes", () => {
const t = translatorFor("zh-CN");
const error = {
version: 1,
code: "DBX-JDBC-2002",
messageKey: "backendErrors.jdbc.operationTimedOut",
messageParams: { stage: "execute" },
source: "jdbcAgent",
operationOutcome: "unknown",
detail: "relation dbx_table_that_does_not_exist does not exist",
} as const;
expect(normalizeBackendError(error)).toEqual(error);
const expected = `${t(error.messageKey, error.messageParams)}\n\n${error.detail}`;
expect(translateBackendError(t, error)).toBe(expected);
expect(translateBackendError(t, new BackendErrorException(error))).toBe(expected);
});
test("shows the database detail after an unclassified Agent summary", () => {
const t = translatorFor("zh-CN");
const error = {
version: 1,
code: "DBX-JDBC-9001",
messageKey: "backendErrors.jdbc.legacyFailure",
messageParams: {},
source: "jdbcAgentLegacy",
operationOutcome: "unknown",
detail: "Table dbx_table_that_does_not_exist does not exist",
} as const;
expect(translateBackendError(t, error)).toBe(`${t(error.messageKey)}\n\n${error.detail}`);
});
test.each([
["array params", { messageParams: ["execute"] }],
["nested params", { messageParams: { stage: { name: "execute" } } }],
["non-finite params", { messageParams: { retryAfter: Number.POSITIVE_INFINITY } }],
["non-string detail", { detail: 42 }],
["object detail", { detail: { message: "database failure" } }],
["unknown source", { source: "http" }],
["unknown outcome", { operationOutcome: "completed" }],
])("rejects malformed structured envelopes with %s", (_name, override) => {
expect(
normalizeBackendError({
version: 1,
code: "DBX-JDBC-2002",
messageKey: "backendErrors.jdbc.operationTimedOut",
messageParams: { stage: "execute" },
source: "jdbcAgent",
operationOutcome: "unknown",
...override,
}),
).toBeNull();
});
test("falls back to legacy text for plain HTTP and Tauri failures", () => {
const t = translatorFor("zh-CN");
const error = new BackendErrorException("legacy backend failure");
expect(error.backendError.code).toBe("DBX-LEGACY-0001");
expect(translateBackendError(t, error)).toBe(`${t("backendErrors.legacy")}\n\nlegacy backend failure`);
});
});
// Matching on message text only works while both sides agree on the wording, so
+12
View File
@@ -1,3 +1,5 @@
import { normalizeBackendError, type BackendError } from "@/lib/backend/errorUtils";
/**
* Minimal shape of a translate function, satisfied by both `useI18n().t` inside
* components and `i18n.global.t` in stores and composables. Using the full
@@ -118,7 +120,17 @@ function backendErrorMessage(error: unknown): string {
return String(error);
}
function translateStructuredBackendError(t: BackendErrorTranslate, error: BackendError): string {
const translated = t(error.messageKey, error.messageParams);
const summary = translated !== error.messageKey ? translated : t("backendErrors.unknown");
const detail = error.detail?.trim();
return detail && detail !== summary ? `${summary}\n\n${detail}` : summary;
}
export function translateBackendError(t: BackendErrorTranslate, error: unknown): string {
const structured = normalizeBackendError(error);
if (structured) return translateStructuredBackendError(t, structured);
const message = backendErrorMessage(error);
const tagged = message.match(/^\[([A-Za-z][A-Za-z0-9]+)\]\s*([\s\S]*)$/);
if (tagged) {
+16
View File
@@ -1517,6 +1517,22 @@ export default {
mcpDescription: "Beyond the built-in AI assistant, you can also use Claude Code, Cursor, and other coding agents to query your databases via MCP.",
mcpLearnMore: "Learn more",
},
backendErrors: {
jdbc: {
connectionFailed: "Database connection failed before the operation started (stage: {stage}).",
connectionInterrupted: "Database connection was interrupted while the operation was running (stage: {stage}).",
operationTimedOut: "Database operation timed out (stage: {stage}).",
operationCanceled: "Database operation was canceled (stage: {stage}).",
busyRetryLater: "Database agent is busy; try again later (stage: {stage}).",
runtimeReplaced: "Database agent runtime was replaced (stage: {stage}).",
sqlFailed: "Database returned an SQL error (stage: {stage}).",
protocolFailed: "Database agent protocol failed.",
contractInvalid: "Database agent returned an invalid error contract.",
legacyFailure: "Database agent returned an unclassified error.",
},
legacy: "Backend returned an error.",
unknown: "An unexpected backend error occurred.",
},
common: {
fileNotFound: "File does not exist: {path}",
language: "Language",
+16
View File
@@ -1459,6 +1459,22 @@ export default withEnglishFallback({
mcpDescription: "Además del asistente de IA integrado, puedes usar Claude Code, Cursor y otros agentes de programación para consultar tus bases de datos mediante MCP.",
mcpLearnMore: "Más información",
},
backendErrors: {
jdbc: {
connectionFailed: "La conexión a la base de datos falló antes de iniciar la operación (fase: {stage}).",
connectionInterrupted: "La conexión a la base de datos se interrumpió durante la operación (fase: {stage}).",
operationTimedOut: "La operación de la base de datos agotó el tiempo de espera (fase: {stage}).",
operationCanceled: "La operación de la base de datos fue cancelada (fase: {stage}).",
busyRetryLater: "El agente de la base de datos está ocupado; inténtalo más tarde (fase: {stage}).",
runtimeReplaced: "Se reemplazó el entorno del agente de la base de datos (fase: {stage}).",
sqlFailed: "La base de datos devolvió un error SQL (fase: {stage}).",
protocolFailed: "Falló el protocolo del agente de la base de datos.",
contractInvalid: "El agente de la base de datos devolvió un contrato de error no válido.",
legacyFailure: "El agente de la base de datos devolvió un error no clasificado.",
},
legacy: "El backend devolvió un error.",
unknown: "Ocurrió un error inesperado del backend.",
},
common: {
fileNotFound: "El archivo no existe: {path}",
language: "Idioma",
+16
View File
@@ -1457,6 +1457,22 @@ export default withEnglishFallback({
mcpDescription: "Oltre all'assistente AI integrato, puoi utilizzare Claude Code, Cursor e altri agenti di sviluppo per interrogare i tuoi database tramite MCP.",
mcpLearnMore: "Scopri di più",
},
backendErrors: {
jdbc: {
connectionFailed: "La connessione al database è fallita prima dell'operazione (fase: {stage}).",
connectionInterrupted: "La connessione al database è stata interrotta durante l'operazione (fase: {stage}).",
operationTimedOut: "L'operazione del database è scaduta (fase: {stage}).",
operationCanceled: "L'operazione del database è stata annullata (fase: {stage}).",
busyRetryLater: "L'agente del database è occupato; riprova più tardi (fase: {stage}).",
runtimeReplaced: "Il runtime dell'agente del database è stato sostituito (fase: {stage}).",
sqlFailed: "Il database ha restituito un errore SQL (fase: {stage}).",
protocolFailed: "Il protocollo dell'agente del database è fallito.",
contractInvalid: "L'agente del database ha restituito un contratto di errore non valido.",
legacyFailure: "L'agente del database ha restituito un errore non classificato.",
},
legacy: "Il backend ha restituito un errore.",
unknown: "Si è verificato un errore backend imprevisto.",
},
common: {
fileNotFound: "Il file non esiste: {path}",
language: "Lingua",
+16
View File
@@ -1484,6 +1484,22 @@ export default withEnglishFallback({
mcpDescription: "内蔵AIアシスタントに加えて、Claude Code、Cursor、その他のコーディングエージェントをMCP経由でデータベースクエリに使用できます。",
mcpLearnMore: "詳細を見る",
},
backendErrors: {
jdbc: {
connectionFailed: "操作開始前にデータベース接続に失敗しました(段階: {stage})。",
connectionInterrupted: "操作中にデータベース接続が中断されました(段階: {stage})。",
operationTimedOut: "データベース操作がタイムアウトしました(段階: {stage})。",
operationCanceled: "データベース操作をキャンセルしました(段階: {stage})。",
busyRetryLater: "データベース Agent が混雑しています。後でもう一度お試しください(段階: {stage})。",
runtimeReplaced: "データベース Agent ランタイムを置き換えました(段階: {stage})。",
sqlFailed: "データベースが SQL エラーを返しました(段階: {stage})。",
protocolFailed: "データベース Agent プロトコルに失敗しました。",
contractInvalid: "データベース Agent が無効なエラー契約を返しました。",
legacyFailure: "データベース Agent が分類できないエラーを返しました。",
},
legacy: "バックエンドがエラーを返しました。",
unknown: "予期しないバックエンドエラーが発生しました。",
},
common: {
fileNotFound: "ファイルが存在しません: {path}",
language: "言語",
+16
View File
@@ -1485,6 +1485,22 @@ export default withEnglishFallback({
mcpDescription: "내장된 AI 어시스턴트 외에도 Claude Code, Cursor 등의 코딩 에이전트를 MCP로 연결하여 데이터베이스를 쿼리할 수 있습니다.",
mcpLearnMore: "더 알아보기",
},
backendErrors: {
jdbc: {
connectionFailed: "작업 시작 전에 데이터베이스 연결에 실패했습니다(단계: {stage}).",
connectionInterrupted: "작업 중 데이터베이스 연결이 중단되었습니다(단계: {stage}).",
operationTimedOut: "데이터베이스 작업 시간이 초과되었습니다(단계: {stage}).",
operationCanceled: "데이터베이스 작업이 취소되었습니다(단계: {stage}).",
busyRetryLater: "데이터베이스 Agent가 사용 중입니다. 나중에 다시 시도하세요(단계: {stage}).",
runtimeReplaced: "데이터베이스 Agent 런타임이 교체되었습니다(단계: {stage}).",
sqlFailed: "데이터베이스에서 SQL 오류를 반환했습니다(단계: {stage}).",
protocolFailed: "데이터베이스 Agent 프로토콜에 실패했습니다.",
contractInvalid: "데이터베이스 Agent가 잘못된 오류 계약을 반환했습니다.",
legacyFailure: "데이터베이스 Agent가 분류되지 않은 오류를 반환했습니다.",
},
legacy: "백엔드에서 오류를 반환했습니다.",
unknown: "예상하지 못한 백엔드 오류가 발생했습니다.",
},
common: {
fileNotFound: "파일이 존재하지 않습니다: {path}",
language: "언어",
+16
View File
@@ -1459,6 +1459,22 @@ export default withEnglishFallback({
mcpDescription: "Além do assistente de IA integrado, você também pode usar Claude Code, Cursor e outros agentes de codificação para consultar seus bancos de dados via MCP.",
mcpLearnMore: "Saiba mais",
},
backendErrors: {
jdbc: {
connectionFailed: "A conexão com o banco falhou antes do início da operação (etapa: {stage}).",
connectionInterrupted: "A conexão com o banco foi interrompida durante a operação (etapa: {stage}).",
operationTimedOut: "A operação do banco excedeu o tempo limite (etapa: {stage}).",
operationCanceled: "A operação do banco foi cancelada (etapa: {stage}).",
busyRetryLater: "O Agent do banco está ocupado; tente novamente mais tarde (etapa: {stage}).",
runtimeReplaced: "O runtime do Agent do banco foi substituído (etapa: {stage}).",
sqlFailed: "O banco retornou um erro SQL (etapa: {stage}).",
protocolFailed: "O protocolo do Agent do banco falhou.",
contractInvalid: "O Agent do banco retornou um contrato de erro inválido.",
legacyFailure: "O Agent do banco retornou um erro não classificado.",
},
legacy: "O backend retornou um erro.",
unknown: "Ocorreu um erro inesperado no backend.",
},
common: {
fileNotFound: "O arquivo não existe: {path}",
language: "Idioma",
+16
View File
@@ -1518,6 +1518,22 @@ export default withEnglishFallback({
mcpDescription: "除了内置 AI 助手,还可以通过 MCP 让 Claude Code、Cursor 等编程助手直接使用这里的数据库连接。",
mcpLearnMore: "了解更多",
},
backendErrors: {
jdbc: {
connectionFailed: "数据库连接在操作开始前失败(阶段:{stage})。",
connectionInterrupted: "数据库连接在操作执行期间中断(阶段:{stage})。",
operationTimedOut: "数据库操作超时(阶段:{stage})。",
operationCanceled: "数据库操作已取消(阶段:{stage})。",
busyRetryLater: "数据库 Agent 忙碌,请稍后重试(阶段:{stage})。",
runtimeReplaced: "数据库 Agent 运行时已替换(阶段:{stage})。",
sqlFailed: "数据库返回了 SQL 错误(阶段:{stage})。",
protocolFailed: "数据库 Agent 协议失败。",
contractInvalid: "数据库 Agent 返回了无效的错误契约。",
legacyFailure: "数据库 Agent 返回了未分类错误。",
},
legacy: "后端返回了错误。",
unknown: "发生了未预期的后端错误。",
},
common: {
fileNotFound: "文件不存在:{path}",
language: "语言",
+16
View File
@@ -1458,6 +1458,22 @@ export default withEnglishFallback({
mcpDescription: "除了內建 AI 助理,也可以藉由 MCP 讓 Claude Code、Cursor 等程式設計助理查詢你的資料庫。",
mcpLearnMore: "了解更多",
},
backendErrors: {
jdbc: {
connectionFailed: "資料庫連線在操作開始前失敗(階段:{stage})。",
connectionInterrupted: "資料庫連線在操作執行期間中斷(階段:{stage})。",
operationTimedOut: "資料庫操作逾時(階段:{stage})。",
operationCanceled: "資料庫操作已取消(階段:{stage})。",
busyRetryLater: "資料庫 Agent 忙碌,請稍後再試(階段:{stage})。",
runtimeReplaced: "資料庫 Agent 執行環境已替換(階段:{stage})。",
sqlFailed: "資料庫回傳了 SQL 錯誤(階段:{stage})。",
protocolFailed: "資料庫 Agent 通訊協定失敗。",
contractInvalid: "資料庫 Agent 回傳了無效的錯誤契約。",
legacyFailure: "資料庫 Agent 回傳了未分類錯誤。",
},
legacy: "後端回傳了錯誤。",
unknown: "發生未預期的後端錯誤。",
},
common: {
fileNotFound: "檔案不存在:{path}",
language: "語言",