/** * Normalizes a rejection reason into a human-readable string. * * Tauri `invoke` rejects with the deserialized Rust error value, which is a * plain object (for example `RuntimeCommandError { code, message }`) rather * than an `Error` instance. Passing such a value to `String()` yields * "[object Object]", so every IPC failure has to go through this helper. */ /** * The Tauri API shim reads `window.__TAURI_INTERNALS__.invoke`, so calling any * command from a plain browser tab throws a `TypeError` about reading 'invoke' * rather than anything a user could act on. The dev server is reachable at * 127.0.0.1:1420, so this is easy to hit by accident. */ const IPC_UNAVAILABLE_PATTERN = /reading ['"]?invoke['"]?|__TAURI_INTERNALS__/; export const IPC_UNAVAILABLE_MESSAGE = "此页面不在 AstrBot Desktop 应用窗口内运行,无法使用本地功能。请在应用中操作。"; export function errorMessage(reason: unknown): string { if (reason instanceof Error) { if (IPC_UNAVAILABLE_PATTERN.test(reason.message)) { return IPC_UNAVAILABLE_MESSAGE; } return reason.message; } if (typeof reason === "string") { return reason; } if (typeof reason === "object" && reason !== null) { const candidate = reason as { message?: unknown; code?: unknown }; if (typeof candidate.message === "string" && candidate.message.length > 0) { return candidate.message; } if (typeof candidate.code === "string" && candidate.code.length > 0) { return candidate.code; } } return String(reason); } /** Rust returns this code when a request was cancelled on purpose. */ export const CANCELLED_ERROR_CODE = "cancelled"; /** True when a rejection reason is a deliberate cancellation rather than a failure. */ export function isCancelledError(reason: unknown): boolean { return ( typeof reason === "object" && reason !== null && (reason as { code?: unknown }).code === CANCELLED_ERROR_CODE ); }