ErrorBoundary

ErrorBoundary

Remix ErrorBoundary 组件的工作方式与普通的 React 错误边界 相同,但具有一些额外的功能。当路由组件出现错误时,ErrorBoundary 将在其位置进行渲染,并嵌套在任何父路由中。当路由的 loaderaction 函数出现错误时,ErrorBoundary 组件也会渲染,因此该路由的所有错误可以在一个地方处理。

¥A Remix ErrorBoundary component works just like normal React error boundaries but with a few extra capabilities. When there is an error in your route component, the ErrorBoundary will be rendered in its place, nested inside any parent routes. ErrorBoundary components also render when there is an error in the loader or action functions for a route, so all errors for that route may be handled in one spot.

最常见的用例往往是:

¥The most common use-cases tend to be:

  • 你可以故意抛出 4xx Response 来触发错误 UI。

    ¥You may intentionally throw a 4xx Response to trigger an error UI

    • 如果用户输入错误,则抛出 400 错误

      ¥Throwing a 400 on bad user input

    • 如果访问未经授权,则抛出 401 错误

      ¥Throwing a 401 for unauthorized access

    • 如果找不到请求的数据,则抛出 404 错误

      ¥Throwing a 404 when you can't find requested data

  • 如果在渲染过程中遇到运行时错误,React 可能会意外抛出 Error 错误。

    ¥React may unintentionally throw an Error if it encounters a runtime error during rendering

要获取抛出的对象,你可以使用 useRouteError 钩子。当抛出 Response 时,它将自动解包为具有 state/statusText/data 字段的 ErrorResponse 实例,因此你无需在组件中使用 await response.json()。要区分抛出的 ResponseError,你可以使用 isRouteErrorResponse 实用程序。

¥To get the thrown object, you can use the useRouteError hook. When a Response is thrown, it will be automatically unwrapped into an ErrorResponse instance with state/statusText/data fields so that you don't need to bother with await response.json() in your component. To differentiate thrown Response's from thrown Error's you can use the isRouteErrorResponse utility.

import {
  isRouteErrorResponse,
  useRouteError,
} from "@remix-run/react";

export function ErrorBoundary() {
  const error = useRouteError();

  if (isRouteErrorResponse(error)) {
    return (
      <div>
        <h1>
          {error.status} {error.statusText}
        </h1>
        <p>{error.data}</p>
      </div>
    );
  } else if (error instanceof Error) {
    return (
      <div>
        <h1>Error</h1>
        <p>{error.message}</p>
        <p>The stack trace is:</p>
        <pre>{error.stack}</pre>
      </div>
    );
  } else {
    return <h1>Unknown Error</h1>;
  }
}
Remix v2.17 中文网 - 粤ICP备13048890号