39 行
1.3 KiB
TypeScript
39 行
1.3 KiB
TypeScript
|
|
/**
|
||
|
|
* 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.
|
||
|
|
*/
|
||
|
|
export function errorMessage(reason: unknown): string {
|
||
|
|
if (reason instanceof Error) {
|
||
|
|
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
|
||
|
|
);
|
||
|
|
}
|