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

@@ -2,6 +2,87 @@
* Utility functions for consistent error handling across the application.
*/
export type BackendErrorParam = string | number | boolean;
export interface BackendError {
version: 1;
code: string;
messageKey: string;
messageParams: Record<string, BackendErrorParam>;
source: "jdbcAgent" | "jdbcAgentLegacy" | "legacyBackend";
operationOutcome: "not_started" | "unknown";
detail?: string;
diagnostics?: Record<string, unknown>;
helpUrl?: string;
}
function isBackendError(value: unknown): value is BackendError {
if (!value || typeof value !== "object") return false;
const candidate = value as Record<string, unknown>;
if (
candidate.version !== 1 ||
typeof candidate.code !== "string" ||
!/^DBX-[A-Z][A-Z0-9]*-\d{4}$/.test(candidate.code) ||
typeof candidate.messageKey !== "string" ||
!candidate.messageKey.startsWith("backendErrors.") ||
!candidate.messageParams ||
typeof candidate.messageParams !== "object" ||
Array.isArray(candidate.messageParams) ||
!["jdbcAgent", "jdbcAgentLegacy", "legacyBackend"].includes(String(candidate.source)) ||
!["not_started", "unknown"].includes(String(candidate.operationOutcome))
) {
return false;
}
if (candidate.detail !== undefined && typeof candidate.detail !== "string") return false;
return Object.values(candidate.messageParams).every((param) => typeof param === "string" || typeof param === "boolean" || (typeof param === "number" && Number.isFinite(param)));
}
export function normalizeBackendError(error: unknown): BackendError | null {
if (error instanceof BackendErrorException) return error.backendError;
if (isBackendError(error)) return error;
if (error && typeof error === "object" && "backendError" in error) {
const backendError = (error as { backendError: unknown }).backendError;
if (isBackendError(backendError)) return backendError;
}
if (error && typeof error === "object" && "error" in error) {
const nested = (error as { error: unknown }).error;
if (isBackendError(nested)) return nested;
}
return null;
}
export class BackendErrorException extends Error {
readonly backendError: BackendError;
constructor(error: unknown) {
const backendError = normalizeRawBackendError(error);
const fallbackMessage = typeof error === "string" ? error : error instanceof Error ? error.message : "Backend request failed";
super(backendError?.detail || fallbackMessage);
this.name = "BackendErrorException";
this.backendError = backendError ?? {
version: 1,
code: "DBX-LEGACY-0001",
messageKey: "backendErrors.legacy",
messageParams: {},
source: "legacyBackend",
operationOutcome: "unknown",
detail: fallbackMessage,
};
}
}
function normalizeRawBackendError(error: unknown): BackendError | null {
if (typeof error === "string") {
try {
const parsed: unknown = JSON.parse(error);
return normalizeBackendError(parsed);
} catch {
return null;
}
}
return normalizeBackendError(error);
}
/**
* Formats an unknown error value into a human-readable string.
* Handles Error objects, strings, null/undefined, and other types.
@@ -17,6 +98,9 @@
* }
*/
export function formatError(e: unknown): string {
const backendError = normalizeBackendError(e);
if (backendError?.detail) return backendError.detail;
if (e instanceof Error) {
return e.message;
}
+18 -6
View File
@@ -45,6 +45,7 @@ import type {
TunnelProfile,
} from "@/types/database";
import { normalizeRustMongoCommand, type MongoCommand } from "@/lib/mongo/mongoShellCommand";
import { BackendErrorException, type BackendError } from "@/lib/backend/errorUtils";
import type { CollectionInfo } from "@/types/database";
import type { SchemaDiffPreparation, SchemaDiffPreparationOptions, TableDiff, FunctionDiff, SequenceDiff, RuleDiff, OwnerDiff } from "@/lib/schema/schemaDiff";
import type { SidebarObjectKind } from "@/lib/database/databaseObjectCapabilities";
@@ -223,19 +224,19 @@ async function post<T>(url: string, body: unknown): Promise<T> {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) throw new Error(await res.text());
if (!res.ok) throw await backendResponseError(res);
return res.json();
}
async function get<T>(url: string): Promise<T> {
const res = await fetch(apiUrl(url));
if (!res.ok) throw new Error(await res.text());
if (!res.ok) throw await backendResponseError(res);
return res.json();
}
async function del<T>(url: string): Promise<T> {
const res = await fetch(apiUrl(url), { method: "DELETE" });
if (!res.ok) throw new Error(await res.text());
if (!res.ok) throw await backendResponseError(res);
return res.json();
}
@@ -245,10 +246,21 @@ async function put<T>(url: string, body: unknown): Promise<T> {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) throw new Error(await res.text());
if (!res.ok) throw await backendResponseError(res);
return res.json();
}
async function backendResponseError(response: Response): Promise<BackendErrorException> {
const text = await response.text();
let payload: unknown = text;
try {
payload = JSON.parse(text);
} catch {
// Preserve legacy plain-text responses at the same compatibility boundary.
}
return new BackendErrorException(payload);
}
function qs(params: Record<string, string | number | boolean | undefined>): string {
const sp = new URLSearchParams();
for (const [k, v] of Object.entries(params)) {
@@ -880,7 +892,7 @@ export interface ExecuteMultiProgress {
success: boolean;
executionTimeMs: number;
affectedRows: number;
error?: string;
error?: BackendError;
}
export async function executeMultiWithProgress(
@@ -918,7 +930,7 @@ export async function executeMultiWithProgress(
success,
executionTimeMs: result.execution_time_ms,
affectedRows: result.affected_rows,
error: success ? undefined : String(result.rows[0]?.[0] ?? ""),
error: success ? undefined : result.error,
});
});
return results;
+28 -17
View File
@@ -1,4 +1,5 @@
import { invoke } from "@tauri-apps/api/core";
import { BackendErrorException, type BackendError } from "@/lib/backend/errorUtils";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { normalizeRustMongoCommand, type MongoCommand } from "@/lib/mongo/mongoShellCommand";
import { ExternalSqlFileTooLargeError } from "@/lib/sql/sqlFileOpen";
@@ -1060,14 +1061,18 @@ export async function executeQuery(
executionMode?: "simple";
},
): Promise<QueryResult> {
return invoke("execute_query", {
connectionId,
database,
sql,
schema,
executionId,
...options,
});
try {
return await invoke("execute_query", {
connectionId,
database,
sql,
schema,
executionId,
...options,
});
} catch (error) {
throw new BackendErrorException(error);
}
}
export async function executeMulti(
@@ -1089,14 +1094,18 @@ export async function executeMulti(
executionMode?: "simple";
},
): Promise<QueryResult[]> {
return invoke("execute_multi", {
connectionId,
database,
sql,
schema,
executionId,
...options,
});
try {
return await invoke("execute_multi", {
connectionId,
database,
sql,
schema,
executionId,
...options,
});
} catch (error) {
throw new BackendErrorException(error);
}
}
export interface ExecuteMultiProgress {
@@ -1107,7 +1116,7 @@ export interface ExecuteMultiProgress {
success: boolean;
executionTimeMs: number;
affectedRows: number;
error?: string;
error?: BackendError;
}
export async function executeMultiWithProgress(
@@ -1137,6 +1146,8 @@ export async function executeMultiWithProgress(
});
try {
return await invoke("execute_multi", { connectionId, database, sql, schema, executionId, ...invokeOptions });
} catch (error) {
throw new BackendErrorException(error);
} finally {
unlisten();
}