错误处理

了解使用 Expo Router 时如何处理应用中不匹配的路由和错误。


本指南指定了使用 Expo Router 时如何处理应用中不匹配的路由和错误。

¥This guide specifies how to handle unmatched routes and errors in your app when using Expo Router.

未匹配的路由

¥Unmatched routes

原生应用没有服务器,因此从技术上讲不存在 404。但是,如果你要实现通用路由,那么处理丢失的路由是有意义的。这是针对每个应用自动补齐的,但你也可以对其进行自定义。

¥Native apps don't have a server so there are technically no 404s. However, if you're implementing a router universally, then it makes sense to handle missing routes. This is done automatically for each app, but you can also customize it.

app/+not-found.tsx
import { Unmatched } from 'expo-router';
export default Unmatched;

这将渲染默认的 Unmatched。你可以导出任何想要渲染的组件。我们建议提供 / 的链接,以便用户可以导航回主屏幕。

¥This will render the default Unmatched. You can export any component you want to render instead. We recommend having a link to / so users can navigate back to the home screen.

错误处理

¥Error handling

Expo Router 支持微调错误处理,以便在未来实现更加有态度的数据加载策略。

¥Expo Router enables fine-tuned error handling to enable a more opinionated data-loading strategy in the future.

你可以从任何路由导出嵌套的 ErrorBoundary 组件,以使用 反应错误边界 拦截和格式化组件级错误:

¥You can export a nested ErrorBoundary component from any route to intercept and format component-level errors using React Error Boundaries:

app/home.tsx
import { View, Text } from 'react-native';
import { type ErrorBoundaryProps } from 'expo-router';

export function ErrorBoundary({ error, retry }: ErrorBoundaryProps) {
  return (
    <View style={{ flex: 1, backgroundColor: "red" }}>
      <Text>{error.message}</Text>
      <Text onPress={retry}>Try Again?</Text>
    </View>
  );
}

export default function Page() { ... }

当你导出 ErrorBoundary 时,路由将被有效的 React Error Boundary 封装:

¥When you export an ErrorBoundary the route will be wrapped with a React Error Boundary effectively:

Virtual
function Route({ ErrorBoundary, Component }) {
  return (
    <Try catch={ErrorBoundary}>
      <Component />
    </Try>
  );
}

ErrorBoundary 不存在时,错误将被抛出到最近的父级 ErrorBoundary 并接受 errorretry 属性。

¥When ErrorBoundary is not present, the error will be thrown to the nearest parent's ErrorBoundary and accepts error and retry props.

尚未完成的

¥Work in progress

React Native LogBox 需要不那么激进地渲染,以便开发时出现错误。目前,它显示 console.errorconsole.warn。然而,理想情况下它应该只显示未捕获的错误。

¥React Native LogBox needs to be presented less aggressively to develop with errors. Currently, it shows for console.error and console.warn. However, it should ideally only show for uncaught errors.