refactor: extract error message handling to utils module

- Move extractErrorMessage function from App.tsx to utils/errorUtils.ts
- Improve code organization and reusability
- Enhance error notification with dynamic message extraction and timeout
This commit is contained in:
Jason
2025-09-17 23:47:17 +08:00
parent 4e9e63f524
commit 19dcc84c83
2 changed files with 44 additions and 1 deletions

View File

@@ -11,6 +11,7 @@ import { UpdateBadge } from "./components/UpdateBadge";
import { Plus, Settings, Moon, Sun } from "lucide-react";
import { buttonStyles } from "./lib/styles";
import { useDarkMode } from "./hooks/useDarkMode";
import { extractErrorMessage } from "./utils/errorUtils";
function App() {
const { isDarkMode, toggleDarkMode } = useDarkMode();
@@ -148,7 +149,11 @@ function App() {
} catch (error) {
console.error("更新供应商失败:", error);
setEditingProviderId(null);
showNotification("保存失败,请重试", "error");
const errorMessage = extractErrorMessage(error);
const message = errorMessage
? `保存失败:${errorMessage}`
: "保存失败,请重试";
showNotification(message, "error", errorMessage ? 6000 : 3000);
}
};

38
src/utils/errorUtils.ts Normal file
View File

@@ -0,0 +1,38 @@
/**
* 从各种错误对象中提取错误信息
* @param error 错误对象
* @returns 提取的错误信息字符串
*/
export const extractErrorMessage = (error: unknown): string => {
if (!error) return "";
if (typeof error === "string") {
return error;
}
if (error instanceof Error && error.message.trim()) {
return error.message;
}
if (typeof error === "object") {
const errObject = error as Record<string, unknown>;
const candidate = errObject.message ?? errObject.error ?? errObject.detail;
if (typeof candidate === "string" && candidate.trim()) {
return candidate;
}
const payload = errObject.payload;
if (typeof payload === "string" && payload.trim()) {
return payload;
}
if (payload && typeof payload === "object") {
const payloadObj = payload as Record<string, unknown>;
const payloadCandidate =
payloadObj.message ?? payloadObj.error ?? payloadObj.detail;
if (typeof payloadCandidate === "string" && payloadCandidate.trim()) {
return payloadCandidate;
}
}
}
return "";
};