/** * Utility functions for consistent error handling across the application. */ /** * Formats an unknown error value into a human-readable string. * Handles Error objects, strings, null/undefined, and other types. * * @param e - The error value to format (from a catch block) * @returns A human-readable error message string * * @example * try { * await someOperation(); * } catch (e: unknown) { * errorMessage.value = formatError(e); * } */ export function formatError(e: unknown): string { if (e instanceof Error) { return e.message; } if (typeof e === "string") { return e; } if (e === null || e === undefined) { return "Unknown error occurred"; } // Try to extract message property from object-like values if (typeof e === "object" && "message" in e) { const message = (e as { message: unknown }).message; if (typeof message === "string") { return message; } } // Fallback: attempt to stringify try { return String(e); } catch { return "Unknown error occurred"; } } /** * Formats an error with a context prefix for better debugging. * * @param e - The error value to format * @param context - The operation context (e.g., "loading topics", "creating tenant") * @returns A formatted error message with context * * @example * catch (e: unknown) { * errorMessage.value = formatErrorWithContext(e, 'loading topics'); * } */ export function formatErrorWithContext(e: unknown, context: string): string { const message = formatError(e); return `Failed to ${context}: ${message}`; }