Просмотр исходного кода

✨ (dashboard-v6): v3 请求统一处理超时与网络错误,加载失败显示错误页

- client.ts:所有 v3 请求加超时(普通 30 秒,上传 / 下载文件 120 秒,计到响应体收完)。
  超时与网络不通不再抛 TypeError 绕过 unwrap,转成 ApiError(kind: timeout / network,
  status 0),与 4xx / 5xx 走同一条路;网关的 408 / 504 也按超时
- error.ts:同一文案的提示只弹一条;新增 dismissApiError()
- 新增 ApiErrorResult(整页错误,按种类给标题与「重试」)与 useLoadGuard(接住
  ProForm / ProTable / ProList 的 request 失败)
- RouteError 显示 loader 抛出的 ApiError 并可重试;term / channel / team 的 loader
  只把 403 / 404 当「不存在」,其余原样抛出;term、team 路由补 errorElement
- fetchChannel 失败时抛出(quiet),不再静默返回 undefined
- 页面:TermEdit、channel 设置 / 关联 / 列表、术语列表、团队列表 / 详情 / 设置、
  句子讨论列表、章节讨论面板、编辑器版本面板、「复制到」版本选择——加载失败只显示
  错误页,不渲染空表单、「暂无数据」或骨架屏

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 3 часов назад
Родитель
Сommit
279902494b
31 измененных файлов с 664 добавлено и 161 удалено
  1. 7 2
      dashboard-v6/src/api/Term.ts
  2. 17 16
      dashboard-v6/src/api/channel.ts
  3. 96 5
      dashboard-v6/src/api/client.ts
  4. 34 4
      dashboard-v6/src/api/error.ts
  5. 15 10
      dashboard-v6/src/api/group.ts
  6. 12 2
      dashboard-v6/src/components/channel/ChannelLinks.tsx
  7. 17 13
      dashboard-v6/src/components/channel/ChannelMy.tsx
  8. 10 0
      dashboard-v6/src/components/channel/ChannelPickerTable.tsx
  9. 14 1
      dashboard-v6/src/components/channel/ChannelTable.tsx
  10. 16 5
      dashboard-v6/src/components/channel/Edit.tsx
  11. 6 2
      dashboard-v6/src/components/channel/hooks/useChannelProgress.ts
  12. 25 3
      dashboard-v6/src/components/discussion/ChapterDiscussionList.tsx
  13. 13 3
      dashboard-v6/src/components/discussion/DiscussionListCard.tsx
  14. 70 0
      dashboard-v6/src/components/general/ApiErrorResult.tsx
  15. 30 1
      dashboard-v6/src/components/general/RouteError.tsx
  16. 17 6
      dashboard-v6/src/components/group/GroupFile.tsx
  17. 19 3
      dashboard-v6/src/components/group/GroupMember.tsx
  18. 135 76
      dashboard-v6/src/components/term/TermEdit.tsx
  19. 10 0
      dashboard-v6/src/components/term/TermList.tsx
  20. 18 2
      dashboard-v6/src/features/group/GroupEdit.tsx
  21. 16 4
      dashboard-v6/src/features/group/GroupList.tsx
  22. 47 0
      dashboard-v6/src/hooks/useLoadGuard.ts
  23. 1 0
      dashboard-v6/src/locales/en-US/buttons.ts
  24. 2 0
      dashboard-v6/src/locales/en-US/label.ts
  25. 1 0
      dashboard-v6/src/locales/zh-Hans/buttons.ts
  26. 2 0
      dashboard-v6/src/locales/zh-Hans/label.ts
  27. 1 0
      dashboard-v6/src/locales/zh-Hant/buttons.ts
  28. 2 0
      dashboard-v6/src/locales/zh-Hant/label.ts
  29. 5 1
      dashboard-v6/src/pages/workspace/channel/show.tsx
  30. 3 1
      dashboard-v6/src/routes/teamRoutes.ts
  31. 3 1
      dashboard-v6/src/routes/termRoutes.ts

+ 7 - 2
dashboard-v6/src/api/Term.ts

@@ -2,6 +2,7 @@ import type { IStudio, IUser, TRole } from "./Auth";
 import type { IChannel } from "./channel";
 import type { LoaderFunctionArgs } from "react-router";
 import { api, unwrap, unwrapQuiet } from "./client";
+import { ApiError } from "./error";
 import type { paths } from "./schema";
 
 /* ─── v3(术语本身已迁 v3,取代 v2 terms 的 show / view=channel|studio|word / store / update / destroy)───
@@ -240,7 +241,11 @@ export async function termLoader({ params }: LoaderFunctionArgs) {
     return unwrapQuiet(
       await api.GET("/v3/terms/{term}", { params: { path: { term: termId } } }),
     ).data;
-  } catch {
-    throw new Response("term not found", { status: 404 });
+  } catch (e) {
+    // 看不见(403)也当不存在;超时、网络不通、5xx 原样抛出,错误页按种类提示并可重试
+    if (e instanceof ApiError && (e.status === 403 || e.status === 404)) {
+      throw new Response("term not found", { status: 404 });
+    }
+    throw e;
   }
 }

+ 17 - 16
dashboard-v6/src/api/channel.ts

@@ -3,6 +3,7 @@ import type { LoaderFunctionArgs } from "react-router";
 import type { IStudio, TRole } from "./Auth";
 import { get } from "../request";
 import { api, unwrap, unwrapQuiet } from "./client";
+import { ApiError } from "./error";
 import type { paths } from "./schema";
 
 /* ─── v3(channel 本身已迁 v3,取代 v2 channel / channel-my-number / channel-progress)─── */
@@ -174,25 +175,25 @@ export async function channelLoader({ params }: LoaderFunctionArgs) {
         params: { path: { channel } },
       }),
     ).data;
-  } catch {
-    throw new Response("Channel not found", { status: 404 });
+  } catch (e) {
+    // 看不见(v3 回 403)也当不存在;超时、网络不通、5xx 原样抛出,错误页按种类提示并可重试
+    if (e instanceof ApiError && (e.status === 403 || e.status === 404)) {
+      throw new Response("Channel not found", { status: 404 });
+    }
+    throw e;
   }
 }
 
-/** 按 uid 取一个 channel;取不到返回 undefined(只用来显示名字之类,不弹错) */
-export const fetchChannel = async (
-  channel: string,
-): Promise<Channel | undefined> => {
-  try {
-    return unwrapQuiet(
-      await api.GET("/v3/channels/{channel}", {
-        params: { path: { channel } },
-      }),
-    ).data;
-  } catch {
-    return undefined;
-  }
-};
+/**
+ * 按 uid 取一个 channel。失败**抛出** ApiError、不弹提示(quiet):
+ * 页面级的调用显示错误页,只拿来显示名字的调用自己 catch 回退。
+ */
+export const fetchChannel = async (channel: string): Promise<Channel> =>
+  unwrapQuiet(
+    await api.GET("/v3/channels/{channel}", {
+      params: { path: { channel } },
+    }),
+  ).data as Channel;
 
 // ─── 获取章节内所有句子 ID ───────────────────────────────────────────────────
 

+ 96 - 5
dashboard-v6/src/api/client.ts

@@ -8,8 +8,8 @@
 import createClient, { type Middleware } from "openapi-fetch";
 
 import { get as getToken } from "../reducers/session";
-import { get as getUiLang } from "../locales";
-import { ApiError, reportApiError } from "./error";
+import { get as getUiLang, messages } from "../locales";
+import { ApiError, type ApiErrorKind, reportApiError } from "./error";
 import type { paths } from "./schema";
 
 /**
@@ -30,6 +30,77 @@ const authMiddleware: Middleware = {
   },
 };
 
+/** 普通请求的超时(从发出到响应体收完) */
+const TIMEOUT_MS = 30_000;
+/** 上传(multipart)与下载文件(不收 JSON)放宽 */
+const FILE_TIMEOUT_MS = 120_000;
+
+/** 前端合成的「请求没成功」响应带这个头,值是 ApiErrorKind(timeout / network) */
+const TRANSPORT_ERROR_HEADER = "X-Client-Transport-Error";
+
+/** 这几个状态码的响应不能带 body(new Response 会抛异常) */
+const NULL_BODY_STATUS = new Set([101, 204, 205, 304]);
+
+/** 界面语言的文案(非组件代码里取不到 useIntl) */
+const text = (id: string): string =>
+  (messages(getUiLang()) as Record<string, string>)[id] ?? id;
+
+const isFileTransfer = (request: Request): boolean =>
+  (request.headers.get("Content-Type") ?? "").startsWith("multipart/") ||
+  !(request.headers.get("Accept") ?? "application/json").includes("json");
+
+/**
+ * 所有 v3 请求经过这里:
+ *
+ * - **超时**:从发出到响应体收完,超过 TIMEOUT_MS 就中止。浏览器的 fetch 本身没有超时,
+ *   后端不回就会一直等下去
+ * - **超时 / 网络不通不抛异常**:openapi-fetch 遇到 fetch 抛异常会原样抛出,绕过
+ *   `unwrap()`——不弹提示、也不是 ApiError,调用方无从区分。这里把它们换成一个合成的
+ *   失败响应(带 TRANSPORT_ERROR_HEADER),于是和 4xx / 5xx 走同一条路:
+ *   `unwrap()` 弹提示并抛 ApiError,`unwrapQuiet()` 只抛
+ * - **调用方自己取消**(传了 signal 并 abort)照旧抛 AbortError,由调用方忽略
+ *
+ * 响应体在这里读完再交出去,超时才能覆盖「响应头到了、正文迟迟不来」的情况。
+ */
+const fetchWithTimeout = async (request: Request): Promise<Response> => {
+  const timeout = AbortSignal.timeout(
+    isFileTransfer(request) ? FILE_TIMEOUT_MS : TIMEOUT_MS,
+  );
+  try {
+    const response = await fetch(request, {
+      signal: AbortSignal.any([request.signal, timeout]),
+    });
+    const body = NULL_BODY_STATUS.has(response.status)
+      ? null
+      : await response.arrayBuffer();
+    // body 已解压,原来的长度与编码头不再对得上
+    const headers = new Headers(response.headers);
+    headers.delete("Content-Length");
+    headers.delete("Content-Encoding");
+    return new Response(body, {
+      status: response.status,
+      statusText: response.statusText,
+      headers,
+    });
+  } catch (e) {
+    if (request.signal.aborted) {
+      throw e;
+    }
+    const kind: ApiErrorKind = timeout.aborted ? "timeout" : "network";
+    return new Response(
+      JSON.stringify({ title: text(`labels.error.${kind}`) }),
+      {
+        // 状态码只是占位(Response 不接受 0),toApiError 认的是 TRANSPORT_ERROR_HEADER
+        status: kind === "timeout" ? 504 : 503,
+        headers: {
+          "Content-Type": "application/problem+json",
+          [TRANSPORT_ERROR_HEADER]: kind,
+        },
+      },
+    );
+  }
+};
+
 /**
  * baseUrl 是 "/api",所以调用时写的是 OpenAPI 规格里的 path(如 "/v3/heartbeat"),
  * 最终请求 "/api/v3/heartbeat"。开发期由 vite proxy 转发到后端。
@@ -38,6 +109,7 @@ export const api = createClient<paths>({
   baseUrl: "/api",
   credentials: "include",
   mode: "cors",
+  fetch: fetchWithTimeout,
 });
 
 api.use(authMiddleware);
@@ -53,12 +125,31 @@ type ProblemDetails = {
 };
 
 const toApiError = (result: FetchResult<unknown>): ApiError => {
-  const problem = result.error as ProblemDetails | undefined;
+  const { response } = result;
+  const transport = response.headers.get(TRANSPORT_ERROR_HEADER);
+  if (transport === "timeout" || transport === "network") {
+    return new ApiError(
+      0,
+      text(`labels.error.${transport}`),
+      undefined,
+      transport,
+    );
+  }
+  // 网关回的 502 / 504 等,响应体是 HTML(openapi-fetch 给的是字符串),没有 detail
+  const problem =
+    typeof result.error === "object"
+      ? (result.error as ProblemDetails | null)
+      : undefined;
+  const kind: ApiErrorKind =
+    response.status === 408 || response.status === 504 ? "timeout" : "http";
   // 422 的字段级错误一并带上,表单可以直接用
   return new ApiError(
-    result.response.status,
-    problem?.detail ?? problem?.title,
+    response.status,
+    problem?.detail ??
+      problem?.title ??
+      (kind === "timeout" ? text("labels.error.timeout") : undefined),
     problem?.errors,
+    kind,
   );
 };
 

+ 34 - 4
dashboard-v6/src/api/error.ts

@@ -12,23 +12,41 @@ import { message } from "antd";
 export type FieldErrors = Record<string, string[]>;
 
 /**
- * v3 接口返回非 2xx 时抛出的错误。
+ * 失败的种类:
+ * - `http`:服务器回了非 2xx
+ * - `timeout`:超时——前端等不到响应(status 0),或网关回 408 / 504
+ * - `network`:请求根本没到服务器(断网、连接被拒),status 0
+ */
+export type ApiErrorKind = "http" | "timeout" | "network";
+
+/**
+ * v3 接口失败时抛出的错误:非 2xx、超时、网络不通都是它(见 client.ts)。
  *
- * message 取自后端 RFC 9457 的 detail,已由后端本地化,前端不用再编文案。
+ * message 取自后端 RFC 9457 的 detail,已由后端本地化;超时与网络不通没有响应体,
+ * 由 client.ts 按界面语言填。
  */
 export class ApiError extends Error {
+  /** HTTP 状态码;超时与网络不通时为 0 */
   readonly status: number;
 
+  readonly kind: ApiErrorKind;
+
   readonly fields?: FieldErrors;
 
   /** 已经提示过,全局兜底据此消掉重复弹窗与控制台噪音 */
   reported = false;
 
-  constructor(status: number, message?: string, fields?: FieldErrors) {
+  constructor(
+    status: number,
+    message?: string,
+    fields?: FieldErrors,
+    kind: ApiErrorKind = "http",
+  ) {
     super(message ?? `HTTP ${status}`);
     this.name = "ApiError";
     this.status = status;
     this.fields = fields;
+    this.kind = kind;
   }
 }
 
@@ -42,7 +60,19 @@ export const fieldErrorsOf = (e: unknown): FieldErrors | undefined =>
  */
 export const reportApiError = (e: ApiError): void => {
   e.reported = true;
-  message.error(e.message);
+  // 同一文案用同一个 key:开发模式 StrictMode、ProTable 重复请求时只留一条,不叠成一串
+  message.error({ content: e.message, key: toastKey(e) });
+};
+
+const toastKey = (e: Error) => `api-error:${e.message}`;
+
+/**
+ * 收掉这条错误的提示。页面已经整页显示了这个错误(ApiErrorResult)时调用,免得提示与错误页重复。
+ */
+export const dismissApiError = (e: unknown): void => {
+  if (e instanceof ApiError) {
+    message.destroy(toastKey(e));
+  }
 };
 
 /**

+ 15 - 10
dashboard-v6/src/api/group.ts

@@ -7,6 +7,7 @@
 import type { LoaderFunctionArgs } from "react-router";
 
 import { api, unwrap, unwrapQuiet, unwrapVoid } from "./client";
+import { ApiError } from "./error";
 import type { paths } from "./schema";
 
 type GroupSingle =
@@ -50,10 +51,14 @@ export async function groupLoader({ params }: LoaderFunctionArgs) {
   }
   try {
     return unwrapQuiet(
-      await api.GET("/v3/groups/{group}", { params: { path: { group } } })
+      await api.GET("/v3/groups/{group}", { params: { path: { group } } }),
     ).data;
-  } catch {
-    throw new Response("team not found", { status: 404 });
+  } catch (e) {
+    // 看不见也当不存在;超时、网络不通、5xx 原样抛出,错误页按种类提示并可重试
+    if (e instanceof ApiError && (e.status === 403 || e.status === 404)) {
+      throw new Response("team not found", { status: 404 });
+    }
+    throw e;
   }
 }
 
@@ -62,7 +67,7 @@ export const searchGroups = async (search: string, perPage = 20) =>
   unwrap(
     await api.GET("/v3/groups", {
       params: { query: { search, per_page: perPage } },
-    })
+    }),
   ).data ?? [];
 
 export const createGroup = async (body: NewGroupInput) =>
@@ -73,33 +78,33 @@ export const updateGroup = async (group: string, body: GroupInput) =>
     await api.PATCH("/v3/groups/{group}", {
       params: { path: { group } },
       body,
-    })
+    }),
   ).data;
 
 /** 名下还有资源时后端 409,unwrapVoid 会弹出原因 */
 export const deleteGroup = async (group: string): Promise<void> =>
   unwrapVoid(
-    await api.DELETE("/v3/groups/{group}", { params: { path: { group } } })
+    await api.DELETE("/v3/groups/{group}", { params: { path: { group } } }),
   );
 
 export const fetchGroupShares = async (
   group: string,
   page: number,
-  perPage: number
+  perPage: number,
 ) =>
   unwrap(
     await api.GET("/v3/groups/{group}/shares", {
       params: { path: { group }, query: { page, per_page: perPage } },
-    })
+    }),
   );
 
 /** 把资源移出团队(只删这条共享,资源本身不动) */
 export const removeGroupShare = async (
   group: string,
-  share: string
+  share: string,
 ): Promise<void> =>
   unwrapVoid(
     await api.DELETE("/v3/groups/{group}/shares/{share}", {
       params: { path: { group, share } },
-    })
+    }),
   );

+ 12 - 2
dashboard-v6/src/components/channel/ChannelLinks.tsx

@@ -30,6 +30,8 @@ import {
   type ChannelRef,
   type EditableChannelQuery,
 } from "../../api/channel";
+import { useLoadGuard } from "../../hooks/useLoadGuard";
+import ApiErrorResult from "../general/ApiErrorResult";
 
 const MAX_FALLBACK = 3;
 const MAX_TERM_SOURCE = 10;
@@ -273,6 +275,8 @@ const ChannelLinksWidget = ({ channelId }: IWidget) => {
   const [links, setLinks] = useState<LinksState>();
   const [channelType, setChannelType] = useState<PickType>();
   const [saving, setSaving] = useState(false);
+  const load = useLoadGuard();
+  const { onError } = load;
 
   useEffect(() => {
     if (!channelId) {
@@ -281,13 +285,19 @@ const ChannelLinksWidget = ({ channelId }: IWidget) => {
     Promise.all([fetchChannelLinks(channelId), fetchChannel(channelId)]).then(
       ([data, channel]) => {
         // channels.type 的取值与列表的 type 过滤参数是同一组(IndexChannelRequest::TYPES)
-        setChannelType(channel?.type as PickType | undefined);
+        setChannelType(channel.type as PickType | undefined);
         if (data) {
           setLinks(toState(data));
         }
       },
+      onError,
     );
-  }, [channelId]);
+  }, [channelId, load.attempt, onError]);
+
+  // 取不到(超时、网络不通…)显示错误页,不再一直停在骨架屏
+  if (load.error) {
+    return <ApiErrorResult error={load.error} onRetry={load.retry} />;
+  }
 
   if (!channelId || !links) {
     return <Skeleton active />;

+ 17 - 13
dashboard-v6/src/components/channel/ChannelMy.tsx

@@ -36,6 +36,7 @@ import NissayaAlignerModal from "../nissaya/NissayaAlignerModal";
 import { useChannelProgress } from "./hooks/useChannelProgress";
 import type { IChannel, IChannelItem } from "../../api/channel";
 import { libraryUrl } from "../../utils";
+import ApiErrorResult from "../general/ApiErrorResult";
 
 const { Search } = Input;
 
@@ -69,7 +70,7 @@ function buildTreeData(
   channelList: IChannelItem[],
   selectedRowKeys: React.Key[],
   owner: string,
-  search?: string
+  search?: string,
 ): ChannelTreeNode[] {
   let ordered: IChannelItem[];
 
@@ -82,17 +83,17 @@ function buildTreeData(
     const seen = new Set(selected.map((v) => v.uid));
 
     const progressing = channelList.filter(
-      (v) => v.progress > 0 && !seen.has(v.uid)
+      (v) => v.progress > 0 && !seen.has(v.uid),
     );
     progressing.forEach((v) => seen.add(v.uid));
 
     const mine = channelList.filter(
-      (v) => v.role === "owner" && !seen.has(v.uid)
+      (v) => v.role === "owner" && !seen.has(v.uid),
     );
     mine.forEach((v) => seen.add(v.uid));
 
     const others = channelList.filter(
-      (v) => !seen.has(v.uid) && v.role !== "member"
+      (v) => !seen.has(v.uid) && v.role !== "member",
     );
 
     ordered = [...selected, ...progressing, ...mine, ...others];
@@ -121,7 +122,7 @@ const ChannelMy = ({
   const intl = useIntl();
   console.debug("ChannelMy render");
   // ── 远程数据(hook 负责全部异步逻辑)──────────────────────────────────────
-  const { channels, sentencesId, sentenceCount, loading, refresh } =
+  const { channels, sentencesId, sentenceCount, loading, error, refresh } =
     useChannelProgress(type, articleId);
 
   // ── 局部 UI 状态 ──────────────────────────────────────────────────────────
@@ -157,7 +158,7 @@ const ChannelMy = ({
   // ── 派生数据:useMemo 替代 useEffect + setState,不产生额外渲染轮次 ──────
   const treeData = useMemo(
     () => buildTreeData(channels, selectedRowKeys, owner, search),
-    [channels, selectedRowKeys, owner, search]
+    [channels, selectedRowKeys, owner, search],
   );
 
   // ── 回调 ──────────────────────────────────────────────────────────────────
@@ -184,7 +185,7 @@ const ChannelMy = ({
 
       if (checked.length > selectedRowKeys.length) {
         const add = checked.filter(
-          (v) => !selectedRowKeys.includes(v.toString())
+          (v) => !selectedRowKeys.includes(v.toString()),
         );
         if (add.length > 0) {
           setSelectedRowKeys((prev) => [...prev, add[0]]);
@@ -193,7 +194,7 @@ const ChannelMy = ({
         setSelectedRowKeys(selectedRowKeys.filter((v) => checked.includes(v)));
       }
     },
-    [selectedRowKeys]
+    [selectedRowKeys],
   );
 
   const handleNodeClick = useCallback(
@@ -201,7 +202,7 @@ const ChannelMy = ({
       setDirty(false);
       onSelect?.([{ id: node.key, name: node.channel.title }]);
     },
-    [onSelect]
+    [onSelect],
   );
 
   // ── titleRender ───────────────────────────────────────────────────────────
@@ -234,7 +235,7 @@ const ChannelMy = ({
       }
 
       const badgeIndex = selectedRowKeys.findIndex(
-        (v) => v === node.channel.uid
+        (v) => v === node.channel.uid,
       );
 
       return (
@@ -338,7 +339,7 @@ const ChannelMy = ({
                       case "library":
                         window.open(
                           libraryUrl(`tipitaka?channel=${ch.id}`),
-                          "_blank"
+                          "_blank",
                         );
                         break;
                     }
@@ -353,7 +354,7 @@ const ChannelMy = ({
         </div>
       );
     },
-    [dirty, selectedRowKeys, handleNodeClick, intl, type, articleId]
+    [dirty, selectedRowKeys, handleNodeClick, intl, type, articleId],
   );
 
   // ── 渲染 ──────────────────────────────────────────────────────────────────
@@ -422,7 +423,10 @@ const ChannelMy = ({
           </Space>
         }
       >
-        {loading ? (
+        {error !== undefined ? (
+          // 加载失败(超时、网络不通…)显示原因,不显示空树
+          <ApiErrorResult error={error} onRetry={refresh} />
+        ) : loading ? (
           <Skeleton active />
         ) : (
           <Tree

+ 10 - 0
dashboard-v6/src/components/channel/ChannelPickerTable.tsx

@@ -26,6 +26,8 @@ import CopyToModal from "./CopyToModal";
 
 import type { ArticleType } from "../../api/article";
 import Studio from "../../../src/components/auth/Studio";
+import { useLoadGuard } from "../../hooks/useLoadGuard";
+import ApiErrorResult from "../general/ApiErrorResult";
 
 const { Link, Text } = Typography;
 
@@ -51,6 +53,7 @@ const ChannelPickerTableWidget = ({
   defaultOwner = "all",
   reload = false,
 }: IWidget) => {
+  const load = useLoadGuard();
   const intl = useIntl();
   const [selectedRowKeys, setSelectedRowKeys] =
     useState<React.Key[]>(selectedKeys);
@@ -68,6 +71,11 @@ const ChannelPickerTableWidget = ({
     }
   }, [reload]);
 
+  // 加载失败(超时、网络不通…)只显示错误页,不显示空列表
+  if (load.error) {
+    return <ApiErrorResult error={load.error} onRetry={load.retry} />;
+  }
+
   return (
     <Space orientation="vertical" style={{ width: "100%" }}>
       {defaultOwner !== "all" && ownerChanged === false ? (
@@ -100,6 +108,8 @@ const ChannelPickerTableWidget = ({
         />
       ) : undefined}
       <ProList<IChannelItem, IParams>
+        onRequestError={load.onError}
+        key={load.attempt}
         actionRef={ref}
         rowSelection={
           showCheckBox

+ 14 - 1
dashboard-v6/src/components/channel/ChannelTable.tsx

@@ -38,6 +38,8 @@ import { TransferOutLinedIcon } from "../../../src/assets/icon";
 import { channelTypeFilter } from "./utils";
 import StatusBadge from "../general/StatusBadge";
 import { EResType } from "../share/utils";
+import { useLoadGuard } from "../../hooks/useLoadGuard";
+import ApiErrorResult from "../general/ApiErrorResult";
 
 const { Text } = Typography;
 
@@ -121,6 +123,7 @@ const ChannelTableWidget = ({
   chapter,
   onSelect,
 }: IWidget) => {
+  const load = useLoadGuard();
   const intl = useIntl();
 
   const [openCreate, setOpenCreate] = useState(false);
@@ -214,6 +217,11 @@ const ChannelTableWidget = ({
 
   const ref = useRef<ActionType | null>(null);
 
+  // 加载失败(超时、网络不通…)只显示错误页,不显示空列表
+  if (load.error) {
+    return <ApiErrorResult error={load.error} onRetry={load.retry} />;
+  }
+
   return (
     <>
       {channelType ? (
@@ -224,6 +232,7 @@ const ChannelTableWidget = ({
         />
       ) : undefined}
       <ProTable<IChannelItem>
+        onRequestError={load.onError}
         actionRef={ref}
         // 与文章列表同一套做法(ArticleList):分页不受控,用 defaultCurrent / defaultPageSize;
         // 除页码外的状态一变就换 key 重新挂载,让新的默认值生效。受控的 current / pageSize 会和
@@ -237,6 +246,8 @@ const ChannelTableWidget = ({
           query.collaborator,
           query.order,
           query.dir,
+          // 「重试」时重新挂载
+          load.attempt,
         ].join("|")}
         columns={[
           {
@@ -531,7 +542,9 @@ const ChannelTableWidget = ({
               }),
             );
             return { total: res?.meta?.total ?? 0, success: true, data: items };
-          } catch {
+          } catch (e) {
+            // 交给页面显示错误页(不是「暂无数据」)
+            load.onError(e);
             return { total: 0, success: false, data: [] };
           }
         }}

+ 16 - 5
dashboard-v6/src/components/channel/Edit.tsx

@@ -20,6 +20,8 @@ import LangSelect from "../general/LangSelect";
 import PublicitySelect from "../studio/PublicitySelect";
 import { useState } from "react";
 import { useAppSelector } from "../../hooks";
+import { useLoadGuard } from "../../hooks/useLoadGuard";
+import ApiErrorResult from "../general/ApiErrorResult";
 import { currentUser } from "../../reducers/current-user";
 
 interface IFormData {
@@ -47,6 +49,13 @@ const EditWidget = ({ channelId, onLoad }: IWidget) => {
   const [data, setData] = useState<Channel>();
 
   const user = useAppSelector(currentUser);
+  const load = useLoadGuard();
+
+  // 取不到 channel(超时、网络不通…)只显示错误页,不渲染空表单
+  if (load.error) {
+    return <ApiErrorResult error={load.error} onRetry={load.retry} />;
+  }
+
   return (
     <>
       {isSystem ? (
@@ -70,12 +79,14 @@ const EditWidget = ({ channelId, onLoad }: IWidget) => {
           } as ChannelInput);
           message.success(intl.formatMessage({ id: "flashes.success" }));
         }}
-        formKey="channel_edit"
-        request={async () => {
-          const channel = channelId ? await fetchChannel(channelId) : undefined;
-          if (!channel) {
+        // formKey 是 request 的缓存键;带上 attempt,「重试」才会真的重新请求
+        formKey={`channel_edit_${load.attempt}`}
+        key={load.attempt}
+        request={load.guard(async () => {
+          if (!channelId) {
             return { name: "", type: "", lang: "", summary: "", status: 0 };
           }
+          const channel = await fetchChannel(channelId);
           setData(channel);
           onLoad?.(channel);
           setIsSystem(channel.is_system);
@@ -90,7 +101,7 @@ const EditWidget = ({ channelId, onLoad }: IWidget) => {
               null) as TChannelSourceType | null,
             source_id: channel.source_id,
           };
-        }}
+        })}
       >
         <ProForm.Group>
           <ProFormText

+ 6 - 2
dashboard-v6/src/components/channel/hooks/useChannelProgress.ts

@@ -32,6 +32,8 @@ interface IUseChannelProgressReturn {
   sentencesId: string[];
   sentenceCount: number;
   loading: boolean;
+  /** 加载失败时的错误(超时、网络不通…);调用方据此显示错误页,不显示空列表 */
+  error: unknown;
   refresh: () => void;
 }
 
@@ -43,6 +45,7 @@ export const useChannelProgress = (
   const [sentencesId, setSentencesId] = useState<string[]>([]);
   const [sentenceCount, setSentenceCount] = useState(0);
   const [loading, setLoading] = useState(true);
+  const [error, setError] = useState<unknown>();
   const [tick, setTick] = useState(0);
 
   // refresh 引用永远稳定,不会触发任何 re-render
@@ -53,6 +56,7 @@ export const useChannelProgress = (
 
     const load = async () => {
       setLoading(true);
+      setError(undefined);
 
       try {
         // ── 1. 解析出句子 ID 列表 ────────────────────────────────────────────
@@ -88,7 +92,7 @@ export const useChannelProgress = (
             .filter((item): item is IChannelItem => item !== undefined),
         );
       } catch (err) {
-        console.error("useChannelProgress fetch error", err);
+        if (active) setError(err);
       } finally {
         if (active) setLoading(false);
       }
@@ -103,5 +107,5 @@ export const useChannelProgress = (
     // tick 由 refresh() 手动递增,是唯一的主动刷新入口
   }, [type, articleId, tick]);
 
-  return { channels, sentencesId, sentenceCount, loading, refresh };
+  return { channels, sentencesId, sentenceCount, loading, error, refresh };
 };

+ 25 - 3
dashboard-v6/src/components/discussion/ChapterDiscussionList.tsx

@@ -15,6 +15,8 @@ import { fetchChannel } from "../../api/channel";
 import DiscussionAuthors from "./DiscussionAuthors";
 import { SeverityTag } from "./SeverityTag";
 import TimeShow from "../general/TimeShow";
+import { useLoadGuard } from "../../hooks/useLoadGuard";
+import ApiErrorResult from "../general/ApiErrorResult";
 
 const { Text } = Typography;
 
@@ -54,6 +56,7 @@ const ChapterDiscussionList = ({
   onOpen,
   onSelect,
 }: IWidget) => {
+  const load = useLoadGuard();
   const { token } = theme.useToken();
   const [selectedId, setSelectedId] = useState<string>();
   const [channel, setChannel] = useState<string | undefined>(channels[0]);
@@ -76,7 +79,14 @@ const ChapterDiscussionList = ({
     if (channels.length < 2) return;
     let alive = true;
     Promise.all(
-      channels.map(async (id) => [id, (await fetchChannel(id))?.name ?? id])
+      // 只为下拉框显示名字;取不到就显示 uid
+      channels.map(async (id) => [
+        id,
+        await fetchChannel(id).then(
+          (c) => c.name ?? id,
+          () => id,
+        ),
+      ]),
     ).then((pairs) => {
       if (alive) setChannelNames(Object.fromEntries(pairs));
     });
@@ -97,8 +107,15 @@ const ChapterDiscussionList = ({
     );
   }
 
+  // 加载失败(超时、网络不通…)只显示错误页,不显示空列表
+  if (load.error) {
+    return <ApiErrorResult error={load.error} onRetry={load.retry} />;
+  }
+
   return (
     <ProList<IComment>
+      onRequestError={load.onError}
+      key={load.attempt}
       rowKey="id"
       onRow={(entity) => ({
         onClick: () => {
@@ -171,7 +188,10 @@ const ChapterDiscussionList = ({
               placeholder="严重程度"
               value={severity}
               onChange={setSeverity}
-              options={SEVERITY_VALUES.map((value) => ({ value, label: value }))}
+              options={SEVERITY_VALUES.map((value) => ({
+                value,
+                label: value,
+              }))}
             />
           ) : undefined}
         </Space>
@@ -201,7 +221,9 @@ const ChapterDiscussionList = ({
                   {entity.title}
                 </Button>
               )}
-              {entity.type !== "discussion" ? <Tag>{entity.type}</Tag> : undefined}
+              {entity.type !== "discussion" ? (
+                <Tag>{entity.type}</Tag>
+              ) : undefined}
               <SeverityTag severity={entity.severity} />
               {status === "all" && entity.status === "close" ? (
                 <Tag>close</Tag>

+ 13 - 3
dashboard-v6/src/components/discussion/DiscussionListCard.tsx

@@ -28,6 +28,8 @@ import {
 import type { ISentenceResponse } from "../../api/sentence";
 import StatusBadge from "../general/StatusBadge";
 import { SeverityTag } from "./SeverityTag";
+import { useLoadGuard } from "../../hooks/useLoadGuard";
+import ApiErrorResult from "../general/ApiErrorResult";
 
 const { Paragraph, Text } = Typography;
 
@@ -52,6 +54,7 @@ const DiscussionListCardWidget = ({
   onItemCountChange,
   onReady,
 }: IWidget) => {
+  const load = useLoadGuard();
   const ref = useRef<ActionType | null>(null);
   const [activeKey, setActiveKey] = useState<TDiscussionStatus>("active");
   const [activeNumber, setActiveNumber] = useState<number>(0);
@@ -77,9 +80,16 @@ const DiscussionListCardWidget = ({
       </Typography.Paragraph>
     );
   }
+  // 加载失败(超时、网络不通…)只显示错误页,不显示空列表
+  if (load.error) {
+    return <ApiErrorResult error={load.error} onRetry={load.retry} />;
+  }
+
   return (
     <>
       <ProList<IComment>
+        onRequestError={load.onError}
+        key={load.attempt}
         rowKey={(row) => row.id ?? `tpl-${row.tplId}`}
         actionRef={ref}
         metas={{
@@ -196,8 +206,8 @@ const DiscussionListCardWidget = ({
           // summary 也会列出批注类型(note / commentary),讨论面板只新建评论线程
           setCreatableTypes(
             THREAD_TYPES.filter((value) =>
-              summary.creatable_types?.includes(value)
-            )
+              summary.creatable_types?.includes(value),
+            ),
           );
           setActiveNumber(summary.status_counts?.active ?? 0);
           setCloseNumber(summary.status_counts?.close ?? 0);
@@ -220,7 +230,7 @@ const DiscussionListCardWidget = ({
                 .filter(
                   (value) =>
                     res.items.findIndex((old) => old.tplId === value.uid) ===
-                    -1
+                    -1,
                 )
                 .map((item) => {
                   return {

+ 70 - 0
dashboard-v6/src/components/general/ApiErrorResult.tsx

@@ -0,0 +1,70 @@
+import { useEffect, type ReactNode } from "react";
+import { Button, Result } from "antd";
+import { useIntl } from "react-intl";
+
+import { ApiError, dismissApiError } from "../../api/error";
+
+interface IWidget {
+  /** 加载失败时 catch 到的东西,一般是 v3 的 ApiError */
+  error: unknown;
+  /** 给了就显示「重试」(401 / 403 / 404 重试也没用,不显示) */
+  onRetry?: () => void;
+  /** 额外的按钮,如「返回」 */
+  extra?: ReactNode;
+}
+
+/**
+ * v3 数据加载失败时的整页错误提示,代替表单 / 内容渲染。
+ *
+ * 超时、网络不通、无权限、不存在、其他错误分别给不同标题;副标题是错误的原文
+ * (后端已本地化的 detail,或 client.ts 填的超时 / 网络文案)。
+ * 挂载时收掉 unwrap() 为同一错误弹的提示,页面上只留这一处。
+ */
+const ApiErrorResult = ({ error, onRetry, extra }: IWidget) => {
+  const intl = useIntl();
+  const label = (id: string) => intl.formatMessage({ id });
+
+  // 整页已经显示了这个错误,unwrap() 弹的同一条提示就多余了
+  useEffect(() => {
+    dismissApiError(error);
+  }, [error]);
+
+  const status = error instanceof ApiError ? error.status : 0;
+  const kind = error instanceof ApiError ? error.kind : "http";
+  const detail = error instanceof Error ? error.message : undefined;
+
+  let resultStatus: "403" | "404" | "warning" | "error" = "error";
+  let title = label("labels.route-error.other");
+  let retryable = true;
+  if (kind === "timeout" || kind === "network") {
+    resultStatus = "warning";
+    title = label(`labels.error.${kind}`);
+  } else if (status === 401) {
+    resultStatus = "403";
+    title = label("labels.error.401");
+    retryable = false;
+  } else if (status === 403 || status === 404) {
+    resultStatus = String(status) as "403" | "404";
+    title = label(`labels.route-error.${status}`);
+    retryable = false;
+  }
+
+  return (
+    <Result
+      status={resultStatus}
+      title={title}
+      // 标题已经说明了的就不重复
+      subTitle={detail && detail !== title ? detail : undefined}
+      extra={[
+        retryable && onRetry ? (
+          <Button key="retry" type="primary" onClick={onRetry}>
+            {label("buttons.retry")}
+          </Button>
+        ) : null,
+        extra ? <span key="extra">{extra}</span> : null,
+      ]}
+    />
+  );
+};
+
+export default ApiErrorResult;

+ 30 - 1
dashboard-v6/src/components/general/RouteError.tsx

@@ -1,6 +1,14 @@
 import { Button, Result } from "antd";
 import { useIntl } from "react-intl";
-import { isRouteErrorResponse, useNavigate, useRouteError } from "react-router";
+import {
+  isRouteErrorResponse,
+  useNavigate,
+  useRevalidator,
+  useRouteError,
+} from "react-router";
+
+import { ApiError } from "../../api/error";
+import ApiErrorResult from "./ApiErrorResult";
 
 interface IWidget {
   /** 「返回」按钮去哪里 */
@@ -10,11 +18,32 @@ interface IWidget {
 /**
  * 路由数据加载失败时的错误页(loader 抛出的 404 / 403 等),代替 React Router 默认的
  * 「Unexpected Application Error」。挂在路由的 errorElement 上。
+ *
+ * loader 原样抛出 v3 的 ApiError 时(超时、网络不通、5xx)按 ApiErrorResult 显示,带「重试」:
+ * 重新跑 loader,成功就回到正常页面。
  */
 const RouteError = ({ backTo = "/workspace" }: IWidget) => {
   const intl = useIntl();
   const navigate = useNavigate();
+  const revalidator = useRevalidator();
   const error = useRouteError();
+
+  const back = (
+    <Button onClick={() => navigate(backTo)}>
+      {intl.formatMessage({ id: "buttons.back" })}
+    </Button>
+  );
+
+  if (error instanceof ApiError) {
+    return (
+      <ApiErrorResult
+        error={error}
+        onRetry={() => revalidator.revalidate()}
+        extra={back}
+      />
+    );
+  }
+
   const status = isRouteErrorResponse(error) ? error.status : 500;
   const known = status === 403 || status === 404;
 

+ 17 - 6
dashboard-v6/src/components/group/GroupFile.tsx

@@ -11,6 +11,8 @@ import {
 import { canManageMembers } from "../../api/group-member";
 import { useAppSelector } from "../../hooks";
 import { currentUser, studioList } from "../../reducers/current-user";
+import { useLoadGuard } from "../../hooks/useLoadGuard";
+import ApiErrorResult from "../general/ApiErrorResult";
 
 const { Content } = Layout;
 
@@ -29,19 +31,27 @@ interface IWidget {
  * 团队的 owner / manager,或资源的拥有者,可以把资源移出团队。
  */
 const GroupFileWidget = ({ groupId }: IWidget) => {
+  const load = useLoadGuard();
   const intl = useIntl(); //i18n
   const [resCount, setResCount] = useState(0);
   const user = useAppSelector(currentUser);
   const studios = useAppSelector(studioList);
   // 管理成员与管理团队文档是同一组角色(owner / manager)
   const canManage = canManageMembers(
-    studios?.find((item) => item.id === groupId)?.role
+    studios?.find((item) => item.id === groupId)?.role,
   );
 
   const ref = useRef<ActionType | null>(null);
+  // 加载失败(超时、网络不通…)只显示错误页,不显示空列表
+  if (load.error) {
+    return <ApiErrorResult error={load.error} onRetry={load.retry} />;
+  }
+
   return (
     <Content>
       <ProList<GroupShare>
+        onRequestError={load.onError}
+        key={load.attempt}
         rowKey="id"
         actionRef={ref}
         // groupId 放进 params:切换团队(团队空间或团队详情页)时 ProList 才会重新请求
@@ -79,8 +89,7 @@ const GroupFileWidget = ({ groupId }: IWidget) => {
           },
           actions: {
             render: (_dom, row) =>
-              canManage ||
-              (user?.id && row.resource?.owner_id === user.id) ? (
+              canManage || (user?.id && row.resource?.owner_id === user.id) ? (
                 <Popconfirm
                   title={intl.formatMessage({
                     id: "forms.message.res.remove",
@@ -88,7 +97,7 @@ const GroupFileWidget = ({ groupId }: IWidget) => {
                   onConfirm={() => {
                     if (groupId && row.id) {
                       removeGroupShare(groupId, row.id).then(() =>
-                        ref.current?.reload()
+                        ref.current?.reload(),
                       );
                     }
                   }}
@@ -110,7 +119,7 @@ const GroupFileWidget = ({ groupId }: IWidget) => {
             const res = await fetchGroupShares(
               groupId,
               params.current ?? 1,
-              params.pageSize ?? 20
+              params.pageSize ?? 20,
             );
             setResCount(res.meta?.total ?? 0);
             return {
@@ -118,7 +127,9 @@ const GroupFileWidget = ({ groupId }: IWidget) => {
               success: true,
               data: res.data ?? [],
             };
-          } catch {
+          } catch (e) {
+            // 交给页面显示错误页(不是「暂无数据」)
+            load.onError(e);
             return { total: 0, success: false, data: [] };
           }
         }}

+ 19 - 3
dashboard-v6/src/components/group/GroupMember.tsx

@@ -18,6 +18,8 @@ import {
 } from "../../api/group-member";
 import { useAppSelector } from "../../hooks";
 import { studioList } from "../../reducers/current-user";
+import { useLoadGuard } from "../../hooks/useLoadGuard";
+import ApiErrorResult from "../general/ApiErrorResult";
 
 const { Content } = Layout;
 
@@ -32,6 +34,7 @@ interface IWidgetGroupFile {
   groupId?: string;
 }
 const GroupMemberWidget = ({ groupId }: IWidgetGroupFile) => {
+  const load = useLoadGuard();
   const intl = useIntl(); //i18n
   const [memberCount, setMemberCount] = useState<number>();
   const studios = useAppSelector(studioList);
@@ -46,9 +49,16 @@ const GroupMemberWidget = ({ groupId }: IWidgetGroupFile) => {
   const ref = useRef<ActionType | null>(null);
   const reload = () => ref.current?.reload();
 
+  // 加载失败(超时、网络不通…)只显示错误页,不显示空列表
+  if (load.error) {
+    return <ApiErrorResult error={load.error} onRetry={load.retry} />;
+  }
+
   return (
     <Content>
       <ProList<GroupMember>
+        onRequestError={load.onError}
+        key={load.attempt}
         rowKey="id"
         actionRef={ref}
         // groupId 放进 params:切换团队(团队空间或团队详情页)时 ProList 才会重新请求
@@ -62,7 +72,11 @@ const GroupMemberWidget = ({ groupId }: IWidgetGroupFile) => {
           canManage && groupId
             ? [
                 <GroupInviteLink key="invite" groupId={groupId} />,
-                <GroupAddMember key="add" groupId={groupId} onCreated={reload} />,
+                <GroupAddMember
+                  key="add"
+                  groupId={groupId}
+                  onCreated={reload}
+                />,
               ]
             : []
         }
@@ -74,7 +88,7 @@ const GroupMemberWidget = ({ groupId }: IWidgetGroupFile) => {
             const res = await fetchGroupMembers(
               groupId,
               params.current ?? 1,
-              params.pageSize ?? 20
+              params.pageSize ?? 20,
             );
             setMemberCount(res.meta?.total);
             return {
@@ -82,7 +96,9 @@ const GroupMemberWidget = ({ groupId }: IWidgetGroupFile) => {
               success: true,
               data: res.data ?? [],
             };
-          } catch {
+          } catch (e) {
+            // 交给页面显示错误页(不是「暂无数据」)
+            load.onError(e);
             return { total: 0, success: false, data: [] };
           }
         }}

+ 135 - 76
dashboard-v6/src/components/term/TermEdit.tsx

@@ -18,6 +18,7 @@ import {
   Dropdown,
   Form,
   Space,
+  Spin,
   Tabs,
   Tag,
 } from "antd";
@@ -49,6 +50,7 @@ import { currentUser as _currentUser } from "../../reducers/current-user";
 import { useActiveStudio } from "../../hooks/useActiveStudio";
 import store from "../../store";
 import { push } from "../../reducers/term-vocabulary";
+import ApiErrorResult from "../general/ApiErrorResult";
 
 interface ValueType {
   key?: string;
@@ -166,6 +168,8 @@ const LeaveGuard = ({
  * - 右上角「取消」「保存」,保存的下拉是「另存为」(弹出版本选择,复制成一条新术语);
  *   两者完成后都调回调,由调用方决定去哪(编辑页回到预览)
  * - 有未保存的修改时,取消 / 离开会提示保存
+ * - 编辑时先从服务器取这条术语;取不到(超时、网络不通、无权限…)只显示错误页与「重试」,
+ *   不渲染表单——空表单看起来像是加载成功了,保存还会静默失败
  */
 const TermEditWidget = ({
   id,
@@ -191,6 +195,10 @@ const TermEditWidget = ({
   const [currChannel, setCurrChannel] = useState<ValueType[]>([]);
   const [etag, setEtag] = useState<string>();
   const [isGeneral, setIsGeneral] = useState(false);
+  /** 表单初始值;undefined = 还在加载 */
+  const [initialValues, setInitialValues] = useState<IFormValues>();
+  const [loadError, setLoadError] = useState<unknown>();
+  const [loadAttempt, setLoadAttempt] = useState(0);
   const user = useAppSelector(_currentUser);
   const { studioId: activeStudioId } = useActiveStudio();
   const { message, modal } = App.useApp();
@@ -233,6 +241,110 @@ const TermEditWidget = ({
     });
   }, [word]);
 
+  /** 表单初始值:编辑时从服务器取,新建时按入口给默认值。失败就抛出(由调用处显示错误页) */
+  const loadInitial = async (): Promise<IFormValues> => {
+    let data: IFormValues = {
+      word: word ? word : "",
+      tag: tags?.join(),
+      meaning: "",
+      meaning2: [],
+      note: "",
+      summary: "",
+      quality: null,
+      content_type: TERM_CONTENT_TYPES[0],
+      redirect: "",
+      lang: "",
+    };
+    if (typeof id !== "undefined") {
+      // 编辑:从服务器拉取。quiet:失败由下面的错误页显示,不再弹提示
+      const term = await fetchTerm(id, {}, true);
+      if (!term) {
+        throw new Error(label("labels.route-error.other"));
+      }
+      setEtag(term.etag);
+      setIsGeneral(!term.channel_id);
+      if (term.channel) {
+        setCurrChannel([
+          { label: term.channel.name, value: term.channel.id ?? "" },
+        ]);
+      }
+      if (parentChannelId) {
+        setCopyToChannel(
+          user?.roles?.includes("basic") ? [parentChannelId] : [""],
+        );
+      }
+      data = {
+        id: community ? undefined : term.id,
+        word: term.word,
+        tag: term.tag ?? undefined,
+        meaning: term.meaning,
+        meaning2: term.other_meaning ? term.other_meaning.split(",") : [],
+        note: term.note ?? "",
+        summary: term.summary ?? "",
+        quality: term.quality ?? null,
+        content_type: term.content_type,
+        redirect: term.redirect ?? "",
+        lang: term.language,
+        channelId: community
+          ? (parentChannelId ?? "")
+          : (term.channel_id ?? ""),
+      };
+      if (!community && !term.abilities?.update) {
+        setReadonly(true);
+      }
+    } else if (typeof parentChannelId !== "undefined") {
+      /**
+       * 在 channel 里新建
+       * basic:只能建在这个版本
+       * pro:在自己的 studio 里默认建成通用术语,在别人的版本里建在版本里
+       */
+      const channel = await fetchChannel(parentChannelId);
+      let target = "";
+      if (user?.roles?.includes("basic")) {
+        target = parentChannelId;
+        setCopyToChannel([parentChannelId]);
+      } else {
+        target = user?.id === parentStudioId ? "" : parentChannelId;
+        setCopyToChannel([channel?.owner?.id ?? "", parentChannelId]);
+      }
+      data = {
+        ...data,
+        lang: channel?.lang ?? "",
+        channelId: target,
+      };
+    } else if (channelId) {
+      // 从版本的术语列表新建
+      data = { ...data, channelId };
+    }
+    return data;
+  };
+
+  // 只在挂载与点「重试」时加载(同原来 ProForm request 的时机);用 ref 取最新的 loadInitial
+  const loadRef = useRef(loadInitial);
+  useEffect(() => {
+    loadRef.current = loadInitial;
+  });
+  useEffect(() => {
+    let cancelled = false;
+    setInitialValues(undefined);
+    setLoadError(undefined);
+    loadRef.current().then(
+      (values) => {
+        if (!cancelled) {
+          setInitialValues(values);
+        }
+      },
+      (e: unknown) => {
+        if (!cancelled) {
+          setLoadError(e);
+        }
+      },
+    );
+    return () => {
+      cancelled = true;
+    };
+  }, [loadAttempt]);
+
   const channelDisable = community || readonly || typeof id !== "undefined";
 
   /** 新建:建在版本里,或建成 studio 级术语 */
@@ -369,6 +481,28 @@ const TermEditWidget = ({
 
   useImperativeHandle(ref, () => ({ cancel: handleCancel }));
 
+  if (loadError !== undefined) {
+    return (
+      <ApiErrorResult
+        error={loadError}
+        onRetry={() => setLoadAttempt((n) => n + 1)}
+        extra={
+          onCancel ? (
+            <Button onClick={onCancel}>{label("buttons.back")}</Button>
+          ) : undefined
+        }
+      />
+    );
+  }
+
+  if (!initialValues) {
+    return (
+      <div style={{ padding: "50px 0", textAlign: "center" }}>
+        <Spin />
+      </div>
+    );
+  }
+
   return (
     <>
       {blockNavigation && (
@@ -432,82 +566,7 @@ const TermEditWidget = ({
         autoFocusFirstInput={true}
         submitter={false}
         onValuesChange={() => setDirty(true)}
-        request={async () => {
-          let data: IFormValues = {
-            word: word ? word : "",
-            tag: tags?.join(),
-            meaning: "",
-            meaning2: [],
-            note: "",
-            summary: "",
-            quality: null,
-            content_type: TERM_CONTENT_TYPES[0],
-            redirect: "",
-            lang: "",
-          };
-          if (typeof id !== "undefined") {
-            // 编辑:从服务器拉取
-            const term = await fetchTerm(id);
-            if (!term) {
-              return data;
-            }
-            setEtag(term.etag);
-            setIsGeneral(!term.channel_id);
-            if (term.channel) {
-              setCurrChannel([
-                { label: term.channel.name, value: term.channel.id ?? "" },
-              ]);
-            }
-            if (parentChannelId) {
-              setCopyToChannel(
-                user?.roles?.includes("basic") ? [parentChannelId] : [""],
-              );
-            }
-            data = {
-              id: community ? undefined : term.id,
-              word: term.word,
-              tag: term.tag ?? undefined,
-              meaning: term.meaning,
-              meaning2: term.other_meaning ? term.other_meaning.split(",") : [],
-              note: term.note ?? "",
-              summary: term.summary ?? "",
-              quality: term.quality ?? null,
-              content_type: term.content_type,
-              redirect: term.redirect ?? "",
-              lang: term.language,
-              channelId: community
-                ? (parentChannelId ?? "")
-                : (term.channel_id ?? ""),
-            };
-            if (!community && !term.abilities?.update) {
-              setReadonly(true);
-            }
-          } else if (typeof parentChannelId !== "undefined") {
-            /**
-             * 在 channel 里新建
-             * basic:只能建在这个版本
-             * pro:在自己的 studio 里默认建成通用术语,在别人的版本里建在版本里
-             */
-            const channel = await fetchChannel(parentChannelId);
-            let target = "";
-            if (user?.roles?.includes("basic")) {
-              target = parentChannelId;
-              setCopyToChannel([parentChannelId]);
-            } else {
-              target = user?.id === parentStudioId ? "" : parentChannelId;
-              setCopyToChannel([channel?.owner?.id ?? "", parentChannelId]);
-            }
-            data = {
-              ...data,
-              lang: channel?.lang ?? "",
-              channelId: target,
-            };
-          } else if (channelId) {
-            // 从版本的术语列表新建
-            data = { ...data, channelId };
-          }
-          return data;
-        }}
+        initialValues={initialValues}
       >
         <Tabs
           items={[

+ 10 - 0
dashboard-v6/src/components/term/TermList.tsx

@@ -22,6 +22,8 @@ import TermModal from "./TermModal";
 import { useAppSelector } from "../../hooks";
 import { currentUser } from "../../reducers/current-user";
 import { Link } from "react-router";
+import { useLoadGuard } from "../../hooks/useLoadGuard";
+import ApiErrorResult from "../general/ApiErrorResult";
 
 interface IItem {
   sn: number;
@@ -43,6 +45,7 @@ interface IWidget {
   channelId?: string;
 }
 const TermListWidget = ({ studioId, studioName, channelId }: IWidget) => {
+  const load = useLoadGuard();
   const intl = useIntl();
   const currUser = useAppSelector(currentUser);
 
@@ -85,9 +88,16 @@ const TermListWidget = ({ studioId, studioName, channelId }: IWidget) => {
         ? { studioId }
         : undefined;
 
+  // 加载失败(超时、网络不通…)只显示错误页,不显示空列表
+  if (load.error) {
+    return <ApiErrorResult error={load.error} onRetry={load.retry} />;
+  }
+
   return (
     <>
       <ProTable<IItem>
+        onRequestError={load.onError}
+        key={load.attempt}
         actionRef={ref}
         columns={[
           {

+ 18 - 2
dashboard-v6/src/features/group/GroupEdit.tsx

@@ -14,6 +14,8 @@ import {
   GROUP_STATUS_PUBLIC,
   updateGroup,
 } from "../../api/group";
+import { useLoadGuard } from "../../hooks/useLoadGuard";
+import ApiErrorResult from "../../components/general/ApiErrorResult";
 
 interface IFormData {
   name: string;
@@ -28,6 +30,12 @@ const GroupEdit = ({ groupId }: IWidget) => {
   const intl = useIntl();
 
   const [title, setTitle] = useState("Loading");
+  const load = useLoadGuard();
+
+  // 取不到团队(超时、网络不通…)只显示错误页,不渲染空表单
+  if (load.error) {
+    return <ApiErrorResult error={load.error} onRetry={load.retry} />;
+  }
 
   return (
     <Card title={title}>
@@ -41,9 +49,17 @@ const GroupEdit = ({ groupId }: IWidget) => {
           setTitle(group?.name ?? values.name);
           message.success(intl.formatMessage({ id: "flashes.success" }));
         }}
-        formKey="group_edit"
+        // formKey 是 request 的缓存键;带上 attempt,「重试」才会真的重新请求
+        formKey={`group_edit_${load.attempt}`}
+        key={load.attempt}
         request={async () => {
-          const group = await fetchGroup(groupId ?? "");
+          let group: Awaited<ReturnType<typeof fetchGroup>>;
+          try {
+            group = await fetchGroup(groupId ?? "");
+          } catch (e) {
+            load.onError(e);
+            throw e;
+          }
           setTitle(group.name ?? "");
           document.title = `${group.name}`;
           return {

+ 16 - 4
dashboard-v6/src/features/group/GroupList.tsx

@@ -19,6 +19,8 @@ import { fetchMyGroupsPage } from "../../api/group-member";
 import StatusBadge from "../../components/general/StatusBadge";
 import { useAppDispatch } from "../../hooks";
 import { refreshMyGroups } from "../teamspace/refreshMyGroups";
+import { useLoadGuard } from "../../hooks/useLoadGuard";
+import ApiErrorResult from "../../components/general/ApiErrorResult";
 
 interface DataItem {
   sn: number;
@@ -36,6 +38,7 @@ interface IWidget {
 }
 /** 我的团队:「我创建的」与「我参加的」两个标签页(v3 /me/groups 的 owned 过滤) */
 const GroupList = ({ onSelect, onSetting }: IWidget) => {
+  const load = useLoadGuard();
   const intl = useIntl(); //i18n
   const dispatch = useAppDispatch();
 
@@ -47,10 +50,10 @@ const GroupList = ({ onSelect, onSetting }: IWidget) => {
   /** 两个标签页的数量:各取一条,读 meta.total */
   const refreshNumbers = useCallback(() => {
     fetchMyGroupsPage({ owned: true, per_page: 1 }).then((res) =>
-      setMyNumber(res.meta?.total ?? 0)
+      setMyNumber(res.meta?.total ?? 0),
     );
     fetchMyGroupsPage({ owned: false, per_page: 1 }).then((res) =>
-      setCollaborationNumber(res.meta?.total ?? 0)
+      setCollaborationNumber(res.meta?.total ?? 0),
     );
   }, []);
   useEffect(refreshNumbers, [refreshNumbers]);
@@ -92,9 +95,16 @@ const GroupList = ({ onSelect, onSetting }: IWidget) => {
 
   const ref = useRef<ActionType | null>(null);
 
+  // 加载失败(超时、网络不通…)只显示错误页,不显示空列表
+  if (load.error) {
+    return <ApiErrorResult error={load.error} onRetry={load.retry} />;
+  }
+
   return (
     <>
       <ProTable<DataItem>
+        onRequestError={load.onError}
+        key={load.attempt}
         actionRef={ref}
         columns={[
           {
@@ -160,7 +170,7 @@ const GroupList = ({ onSelect, onSetting }: IWidget) => {
                     id: `labels.group.role.${role}`,
                   }),
                 },
-              ])
+              ]),
             ),
           },
           {
@@ -243,7 +253,9 @@ const GroupList = ({ onSelect, onSetting }: IWidget) => {
                 : undefined,
             }));
             return { total: res.meta?.total ?? 0, success: true, data: items };
-          } catch {
+          } catch (e) {
+            // 交给页面显示错误页(不是「暂无数据」)
+            load.onError(e);
             return { total: 0, success: false, data: [] };
           }
         }}

+ 47 - 0
dashboard-v6/src/hooks/useLoadGuard.ts

@@ -0,0 +1,47 @@
+import { useCallback, useState } from "react";
+
+/**
+ * 页面级数据加载失败的统一接法。
+ *
+ * pro-components 的 `request` 失败时:ProForm 把异常吞掉、照样渲染空表单;ProTable / ProList
+ * 停在空数据上显示「暂无数据」。看起来都像「加载成功但没有内容」。用这个 hook 把失败接住,
+ * 组件改为渲染 `<ApiErrorResult error={load.error} onRetry={load.retry} />`,不渲染表单或表格。
+ *
+ * ```tsx
+ * const load = useLoadGuard();
+ * if (load.error) return <ApiErrorResult error={load.error} onRetry={load.retry} />;
+ * <ProTable key={load.attempt} onRequestError={load.onError} request={...} />
+ * <ProForm key={load.attempt} request={load.guard(async () => ...)} />
+ * <useEffect>  fetchX().then(set, load.onError)  // 依赖里放 load.attempt
+ * ```
+ *
+ * 「重试」清掉错误并让 `attempt` 加一:把它放进 `key` 让组件重新挂载(重新请求),
+ * 或放进 useEffect 的依赖。
+ */
+export const useLoadGuard = () => {
+  const [error, setError] = useState<unknown>();
+  const [attempt, setAttempt] = useState(0);
+
+  const onError = useCallback((e: unknown) => setError(e), []);
+
+  /** 包一层 ProForm 的 request:失败时记下错误再抛出 */
+  const guard = useCallback(
+    <A extends unknown[], R>(fn: (...args: A) => Promise<R>) =>
+      async (...args: A): Promise<R> => {
+        try {
+          return await fn(...args);
+        } catch (e) {
+          setError(e);
+          throw e;
+        }
+      },
+    [],
+  );
+
+  const retry = useCallback(() => {
+    setError(undefined);
+    setAttempt((n) => n + 1);
+  }, []);
+
+  return { error, attempt, onError, guard, retry };
+};

+ 1 - 0
dashboard-v6/src/locales/en-US/buttons.ts

@@ -120,6 +120,7 @@ const items = {
   "buttons.account.switch": "Switch account",
   "buttons.teamspace.leave": "Back to personal space",
   "buttons.back": "Back",
+  "buttons.retry": "Retry",
   "buttons.group.invite.link": "Get Invite Link",
   "buttons.group.invite.accept": "Accept and Join",
   "buttons.group.invite.sign-in": "Sign in to Join",

+ 2 - 0
dashboard-v6/src/locales/en-US/label.ts

@@ -60,6 +60,8 @@ const items = {
   "labels.error.403": "没有权限",
   "labels.error.404": "没有找到指定的资源",
   "labels.error.429": "请求过于频繁",
+  "labels.error.timeout": "Request timed out: the server did not respond in time",
+  "labels.error.network": "Cannot reach the server. Please check your network",
   "labels.error.500": "Server Internal Error",
   "labels.error.render-failed": "Diagram failed to render",
   "labels.task": "task",

+ 1 - 0
dashboard-v6/src/locales/zh-Hans/buttons.ts

@@ -121,6 +121,7 @@ const items = {
   "buttons.account.switch": "切换账号",
   "buttons.teamspace.leave": "切回个人空间",
   "buttons.back": "返回",
+  "buttons.retry": "重试",
   "buttons.group.invite.link": "获取邀请链接",
   "buttons.group.invite.accept": "同意加入",
   "buttons.group.invite.sign-in": "登录后加入",

+ 2 - 0
dashboard-v6/src/locales/zh-Hans/label.ts

@@ -65,6 +65,8 @@ const items = {
   "labels.error.403": "没有权限",
   "labels.error.404": "没有找到指定的资源",
   "labels.error.429": "请求过于频繁",
+  "labels.error.timeout": "请求超时,服务器没有在规定时间内响应",
+  "labels.error.network": "无法连接服务器,请检查网络",
   "labels.error.500": "服务器内部错误",
   "labels.error.render-failed": "图形渲染失败",
   "labels.task": "任务",

+ 1 - 0
dashboard-v6/src/locales/zh-Hant/buttons.ts

@@ -121,6 +121,7 @@ const items = {
   "buttons.account.switch": "切換帳號",
   "buttons.teamspace.leave": "切回個人空間",
   "buttons.back": "返回",
+  "buttons.retry": "重試",
   "buttons.group.invite.link": "取得邀請連結",
   "buttons.group.invite.accept": "同意加入",
   "buttons.group.invite.sign-in": "登入後加入",

+ 2 - 0
dashboard-v6/src/locales/zh-Hant/label.ts

@@ -65,6 +65,8 @@ const items = {
   "labels.error.403": "沒有權限",
   "labels.error.404": "沒有找到指定的資源",
   "labels.error.429": "請求過於頻繁",
+  "labels.error.timeout": "請求逾時,伺服器沒有在規定時間內回應",
+  "labels.error.network": "無法連線伺服器,請檢查網路",
   "labels.error.500": "伺服器內部錯誤",
   "labels.error.render-failed": "圖形渲染失敗",
   "labels.task": "任務",

+ 5 - 1
dashboard-v6/src/pages/workspace/channel/show.tsx

@@ -26,7 +26,11 @@ const Widget = () => {
 
   useEffect(() => {
     if (channelId) {
-      fetchChannel(channelId).then((channel) => setTitle(channel?.name));
+      // 只为标签页标题;取不到就用默认标题(页面本身由路由 loader 负责报错)
+      fetchChannel(channelId).then(
+        (channel) => setTitle(channel.name),
+        () => setTitle(undefined),
+      );
     }
   }, [channelId]);
   return (

+ 3 - 1
dashboard-v6/src/routes/teamRoutes.ts

@@ -1,7 +1,8 @@
 // src/routes/channelRoutes.ts
-import { lazy } from "react";
+import { createElement, lazy } from "react";
 import type { RouteObject } from "react-router";
 import { groupLoader } from "../api/group";
+import RouteError from "../components/general/RouteError";
 
 const WorkspaceTeam = lazy(() => import("../pages/workspace/team"));
 const WorkspaceTeamShow = lazy(() => import("../pages/workspace/team/show"));
@@ -26,6 +27,7 @@ const channelRoutes: RouteObject[] = [
       {
         path: ":teamId",
         loader: groupLoader,
+        errorElement: createElement(RouteError, { backTo: "/workspace/team" }),
         handle: {
           crumb: (match: { data?: { name?: string } }) =>
             match.data?.name ?? "",

+ 3 - 1
dashboard-v6/src/routes/termRoutes.ts

@@ -1,7 +1,8 @@
 // src/routes/termRoutes.ts
-import { lazy } from "react";
+import { createElement, lazy } from "react";
 import type { RouteObject } from "react-router";
 import { termLoader } from "../api/Term";
+import RouteError from "../components/general/RouteError";
 
 const WorkspaceTerm = lazy(() => import("../pages/workspace/term/list"));
 const WorkspaceTermShow = lazy(() => import("../pages/workspace/term/show"));
@@ -19,6 +20,7 @@ const termRoutes: RouteObject[] = [
       {
         path: ":id",
         loader: termLoader,
+        errorElement: createElement(RouteError, { backTo: "/workspace/term" }),
         handle: {
           crumb: (match: { data: { word: string } }) => match.data.word,
         },