Ordo UI
PatternsFeedback

ErrorBoundary

@mox-hub/patterns 模式 · Feedback · canonical

error-boundary@mox-hub/patternsFeedbackcanonicalsrc/components/error-boundary.tsx
变体演示error-boundary

子树正常渲染

Props API

Prop类型默认值说明
children*ReactNode——
fallbackReactNode——
errorCodestring—错误码前缀,如 "E500"、"E404"、"EERR"
onError(error: Error, errorInfo: ErrorInfo) => void—错误上报回调
homeHrefstring—首页链接(缺省 /app;路由型消费方传自己的首页地址)
labelsPartial<ErrorBoundaryLabels>—文案覆写;class 组件不能直接用 hook,Provider 场景请由父级传入

源码

packages/patterns/src/components/error-boundary.tsx
import { Component, type ErrorInfo, type ReactNode } from "react"
import { AlertTriangleIcon, RefreshCwIcon, HomeIcon } from "lucide-react"
import { Alert, AlertDescription } from "@mox-hub/ui/components/alert"
import { Button, buttonVariants } from "@mox-hub/ui/components/button"
import { usePatternLabels } from "../lib/i18n"

export interface ErrorBoundaryLabels {
  error: string
  fallbackMessage: string
  reload: string
  home: string
}

const DEFAULT_LABELS: ErrorBoundaryLabels = {
  error: '发生错误',
  fallbackMessage: '一个意外的错误发生了',
  reload: '刷新页面',
  home: '返回首页',
}

export interface ErrorBoundaryProps {
  children: ReactNode
  fallback?: ReactNode
  /** 错误码前缀,如 "E500"、"E404"、"EERR" */
  errorCode?: string
  /** 错误上报回调 */
  onError?: (error: Error, errorInfo: ErrorInfo) => void
  /** 首页链接(缺省 /app;路由型消费方传自己的首页地址) */
  homeHref?: string
  /** 文案覆写;class 组件不能直接用 hook,Provider 场景请由父级传入 */
  labels?: Partial<ErrorBoundaryLabels>
}

interface State {
  hasError: boolean
  error: Error | null
}

class ErrorBoundaryImpl extends Component<ErrorBoundaryProps, State> {
  constructor(props: ErrorBoundaryProps) {
    super(props)
    this.state = { hasError: false, error: null }
  }

  static getDerivedStateFromError(error: Error): State {
    return { hasError: true, error }
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error("[ErrorBoundary]", error, errorInfo)
    this.props.onError?.(error, errorInfo)
  }

  render() {
    if (this.state.hasError) {
      if (this.props.fallback) {
        return this.props.fallback
      }

      const code = this.props.errorCode ?? "EERR"
      const homeHref = this.props.homeHref ?? "/app"
      const L = { ...DEFAULT_LABELS, ...this.props.labels }

      return (
        <div className="flex min-h-100 flex-col items-center justify-center gap-6 p-6">
              <Alert variant="destructive" className="max-w-md w-full" role="alert">
            <AlertTriangleIcon className="size-4 text-destructive" />
            <AlertDescription className="flex flex-col gap-4">
              <div className="flex flex-col gap-1">
                <div className="flex items-center gap-2">
                  <span className="font-mono text-xs font-semibold text-destructive">
                    {code}
                  </span>
                  <span className="font-semibold text-destructive">{L.error}</span>
                </div>
                <p className="text-sm text-destructive/80">
                  {this.state.error?.message || L.fallbackMessage}
                </p>
              </div>
              <div className="flex gap-2">
                <Button
                  size="sm"
                  onClick={() => {
                    this.setState({ hasError: false, error: null })
                    window.location.reload()
                  }}
                >
                  <RefreshCwIcon className="size-3.5 me-1.5" />
                  {L.reload}
                </Button>
                <a
                  href={homeHref}
                  className={buttonVariants({ variant: "outline", size: "sm" })}
                >
                  <HomeIcon className="size-3.5 me-1.5" />
                  {L.home}
                </a>
              </div>
            </AlertDescription>
          </Alert>
        </div>
      )
    }

    return this.props.children
  }
}

/**
 * Provider-aware 入口:class 组件不能直接用 hook,由函数壳读取
 * I18nProvider 的 errorBoundary section,再与显式 labels 合并后交给内部 class。
 */
export function ErrorBoundary({ ...props }: ErrorBoundaryProps) {
  const D = usePatternLabels("errorBoundary", DEFAULT_LABELS)
  return <ErrorBoundaryImpl {...props} labels={{ ...D, ...props.labels }} />
}

可访问性与 RTL

  • 键盘:交互件保留:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。
  • RTL:间距、对齐与方向性图标使用逻辑属性 (ms-* /text-start /rtl:-scale-x-100);通过 ThemeProvider 或I18nProvider 的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。
  • 文案:优先用组件labels /translate /translator props,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。
  • 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。

用法说明

类组件错误边界:捕获子树错误,渲染默认错误卡或 fallback;onError 上报,homeHref 可覆写首页。