Corp/frontend/src/lib/errors.ts

30 lines
934 B
TypeScript

type ApiErrorShape = {
message?: unknown;
response?: { data?: unknown };
};
export function getErrorMessage(error: unknown, fallback: string): string {
if (error instanceof Error && error.message) return error.message;
if (typeof error === "object" && error !== null) {
const message = (error as ApiErrorShape).message;
if (typeof message === "string" && message) return message;
}
return fallback;
}
export function getFieldError(
error: unknown,
field: string,
fallback: string,
): string {
if (typeof error === "object" && error !== null) {
const data = (error as ApiErrorShape).response?.data;
if (typeof data === "object" && data !== null) {
const value = (data as Record<string, unknown>)[field];
if (Array.isArray(value) && typeof value[0] === "string") return value[0];
if (typeof value === "string") return value;
}
}
return getErrorMessage(error, fallback);
}