lang
lang/typescript/error-handling/index.md
medium
typescript-error-handling-index
TypeScript 错误处理 — ApiError 子类 + Asserts 工具 + 路由级 ErrorBoundary
子项索引
| 子项 | 一句话 |
|---|---|
| api-error-class skill | ApiError extends Error 子类设计 + fetcher 集成 + 与后端 ApiException 对齐 |
| assert-helpers skill | Asserts 工具集 + asserts value is T 谓词收窄类型 + 11 个常用断言方法 |
| error-boundary skill | Next.js App Router 路由级 ErrorBoundary — app/error.tsx + "use client" + ApiError.code 分流 fallback |
| form-error-handling skill | antd Form 提交局部 catch ApiError + 字段映射 — 比 ErrorBoundary 更细,比 Form rules 更全 |
TypeScript · Error Handling
一句话
前端镜像后端 ApiException 模型:ApiError extends Error(含 code + httpStatus + data),Asserts.<方法> 失败抛 ApiError,路由级 ErrorBoundary 按 code 前缀分流。
推荐落点
| 文件 | 内容 |
|---|---|
frontend/app/lib/assertion.ts |
ApiError + Asserts 方法集合 |
frontend/app/lib/api.ts |
fetcher 抛 ApiError(替换原 new Error(...)) |
frontend/app/error.tsx |
路由级 ErrorBoundary,按 code 前缀路由 fallback 标题 |
何时下钻
| 任务 | 选哪个子项 |
|---|---|
| 写 fetcher / 调 API | api-error-class |
| 写表单 / 客户端校验 | assert-helpers + form-error-handling |
| 设计页面级错误兜底 | error-boundary |
| 表单字段绑定错误 | form-error-handling |
与后端的对齐
后端 ApiException(code, message, http_status, data)
↓ FastAPI JSON 序列化 detail = {code, message, data}
↓ HTTP 响应(status_code = http_status)
↓
前端 fetcher 抛 ApiError({code, message, httpStatus, data})
↓ ErrorBoundary 按 code.charAt(0) 路由