---
id: error-boundaries
track: learn
product: router
locale: zh-CN
order: 7
revision: 2
sourceCheckedOn: "2026-08-03"
versionRange: "Start ^1 / Router ^1"
verifiedAgainst: "@tanstack/react-start@1.168.34 + @tanstack/react-router@1.170.18"
contentModel: 2
prerequisites:
  - "理解路由树与 Loader"
sourceRefs:
  - "https://tanstack.com/start/latest/docs/framework/react/guide/error-boundaries"
---

# 把错误关在正确的路由里

> 用全局默认错误界面兜底，用 route errorComponent 隔离局部数据或渲染失败。

**Outcome:** 能为 Loader 与组件错误提供可恢复、不会泄露内部信息的界面。

## 错误沿路由树向上冒泡

Loader 或路由组件抛出的错误会交给最近的 errorComponent。产品级应用应在 Router 上设置 defaultErrorComponent，再为需要独立恢复的页面覆盖它。

## 提供重试，不展示堆栈

reset 会重置错误边界。面向用户的界面应使用稳定文案；详细错误进入受控日志，而不是直接渲染可能包含内部信息的 message。

File: `src/routes/issues/index.tsx`

```tsx
import type { ErrorComponentProps } from '@tanstack/react-router'

export const Route = createFileRoute('/issues/')({
  loader: loadIssues,
  errorComponent: IssuesError,
  component: IssuesPage,
})

function IssuesError({ reset }: ErrorComponentProps) {
  return (
    <section role="alert">
      <h1>Issues could not be loaded.</h1>
      <button onClick={reset}>Try again</button>
    </section>
  )
}
```

## 实践与验证

### 完成检查点

Loader 或渲染错误被最近的路由 errorComponent 捕获，兄弟路由仍可导航。

### 动手练习

让一个不存在的 Issue 抛出 notFound，并让网络故障进入可重试的 errorComponent。

### 验证方法

分别触发 404 和 500；页面文案、状态与恢复动作应不同，导航栏保持可用。

### 常见错误

- 把 404、重定向和未知异常都渲染成同一错误。
- 在 errorComponent 中重试却不重置路由状态。

## Official sources

- https://tanstack.com/start/latest/docs/framework/react/guide/error-boundaries
