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:
@@ -11,6 +11,7 @@ import { UpdateBadge } from "./components/UpdateBadge";
|
|||||||
import { Plus, Settings, Moon, Sun } from "lucide-react";
|
import { Plus, Settings, Moon, Sun } from "lucide-react";
|
||||||
import { buttonStyles } from "./lib/styles";
|
import { buttonStyles } from "./lib/styles";
|
||||||
import { useDarkMode } from "./hooks/useDarkMode";
|
import { useDarkMode } from "./hooks/useDarkMode";
|
||||||
|
import { extractErrorMessage } from "./utils/errorUtils";
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
const { isDarkMode, toggleDarkMode } = useDarkMode();
|
const { isDarkMode, toggleDarkMode } = useDarkMode();
|
||||||
@@ -148,7 +149,11 @@ function App() {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("更新供应商失败:", error);
|
console.error("更新供应商失败:", error);
|
||||||
setEditingProviderId(null);
|
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
38
src/utils/errorUtils.ts
Normal 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 "";
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user