ERP-node/frontend/lib/utils/toastUtils.ts

83 lines
2.2 KiB
TypeScript
Raw Normal View History

import { toast } from "sonner";
/**
* /catch
*/
function extractErrorMessage(error: unknown): string | null {
if (!error) return null;
if (error instanceof Error) {
return error.message;
}
if (typeof error === "string") {
return error;
}
if (typeof error === "object" && error !== null) {
const obj = error as Record<string, any>;
return (
obj.response?.data?.message ||
obj.response?.data?.error ||
obj.message ||
obj.error ||
null
);
}
return null;
}
/**
* .
*
* @param title - (: "메뉴 저장에 실패했습니다")
* @param error - catch error
* @param options -
* @param options.guidance - (: "네트워크 연결을 확인해 주세요")
* @param options.duration - (ms)
*/
export function showErrorToast(
title: string,
error?: unknown,
options?: {
guidance?: string;
duration?: number;
}
) {
const errorMessage = extractErrorMessage(error);
const guidance = options?.guidance;
const descriptionParts: string[] = [];
if (errorMessage) descriptionParts.push(errorMessage);
if (guidance) descriptionParts.push(guidance);
const description =
descriptionParts.length > 0 ? descriptionParts.join("\n") : undefined;
toast.error(title, {
description,
duration: options?.duration || 5000,
});
}
/**
* API
* API .
*/
export function showApiErrorToast(
action: string,
response?: { message?: string; error?: string } | null,
fallbackError?: unknown
) {
const apiMessage = response?.message || response?.error;
const errorMessage = apiMessage || extractErrorMessage(fallbackError);
const description = errorMessage || "잠시 후 다시 시도해 주세요.";
toast.error(`${action}에 실패했습니다`, {
description,
duration: 5000,
});
}