diff --git a/content/docs/error-boundaries.md b/content/docs/error-boundaries.md index 147732911..9e1496316 100644 --- a/content/docs/error-boundaries.md +++ b/content/docs/error-boundaries.md @@ -1,28 +1,28 @@ --- id: error-boundaries -title: Error Boundaries +title: Error Boundary permalink: docs/error-boundaries.html --- -In the past, JavaScript errors inside components used to corrupt React’s internal state and cause it to [emit](https://github.com/facebook/react/issues/4026) [cryptic](https://github.com/facebook/react/issues/6895) [errors](https://github.com/facebook/react/issues/8579) on next renders. These errors were always caused by an earlier error in the application code, but React did not provide a way to handle them gracefully in components, and could not recover from them. +かつて、コンポーネント内で発生した JavaScript エラーは React の内部状態を破壊し、以降のレンダーで[不可解な](https://github.com/facebook/react/issues/4026) [エラーを](https://github.com/facebook/react/issues/6895) [引き起こして](https://github.com/facebook/react/issues/8579)いました。このようなエラーはアプリケーションコード中のどこか前の段階で発生したエラーによって引き起こされますが、React はエラーをコンポーネント内で適切に処理する方法を提供していなかったため回復できませんでした。 -## Introducing Error Boundaries {#introducing-error-boundaries} +## error boundary とは {#introducing-error-boundaries} -A JavaScript error in a part of the UI shouldn’t break the whole app. To solve this problem for React users, React 16 introduces a new concept of an “error boundary”. +UI の一部に JavaScript エラーがあってもアプリ全体が壊れてはいけません。React ユーザーがこの問題に対応できるように、React 16 では “error boundary” という新しい概念を導入しました。 -Error boundaries are React components that **catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI** instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them. +error boundary は**自身の子コンポーネントツリーで発生した JavaScript エラーをキャッチ**し、**エラーを記録**し、クラッシュしたコンポーネントツリーの代わりに**フォールバック用の UI を表示**する React コンポーネントです。error boundary は配下のツリー全体のレンダー中、ライフサイクルメソッド内、およびコンストラクタ内で発生したエラーをキャッチします。 -> Note +> 補足 > -> Error boundaries do **not** catch errors for: +> error boundary は以下のエラーをキャッチ**しません**: > -> * Event handlers ([learn more](#how-about-event-handlers)) -> * Asynchronous code (e.g. `setTimeout` or `requestAnimationFrame` callbacks) -> * Server side rendering -> * Errors thrown in the error boundary itself (rather than its children) +> * イベントハンドラ([詳細](#how-about-event-handlers)) +> * 非同期コード(例:`setTimeout` や `requestAnimationFrame` のコールバック) +> * サーバーサイドレンダリング +> * (子コンポーネントではなく)error boundary 自身がスローしたエラー -A class component becomes an error boundary if it defines either (or both) of the lifecycle methods [`static getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror) or [`componentDidCatch()`](/docs/react-component.html#componentdidcatch). Use `static getDerivedStateFromError()` to render a fallback UI after an error has been thrown. Use `componentDidCatch()` to log error information. +クラスコンポーネントに、ライフサイクルメソッドの [`static getDerivedStateFromError()`](/docs/react-component.html#static-getderivedstatefromerror) か [`componentDidCatch()`](/docs/react-component.html#componentdidcatch) のいずれか(または両方)を定義すると、error boundary になります。`static getDerivedStateFromError()` はエラーがスローされた後にフォールバック UI をレンダーするために使用します。 `componentDidCatch()` はエラー情報をログに記録するために使用します。 ```js{7-10,12-15,18-21} class ErrorBoundary extends React.Component { @@ -52,7 +52,7 @@ class ErrorBoundary extends React.Component { } ``` -Then you can use it as a regular component: +使用する際は通常のコンポーネントとして扱います: ```js @@ -60,53 +60,53 @@ Then you can use it as a regular component: ``` -Error boundaries work like a JavaScript `catch {}` block, but for components. Only class components can be error boundaries. In practice, most of the time you’ll want to declare an error boundary component once and use it throughout your application. +error boundary はコンポーネントに対して JavaScript の `catch {}` ブロックのように動作します。error boundary になれるのはクラスコンポーネントだけです。実用上、一度だけ error boundary を定義してそれをアプリケーションの至るところで使用することがよくあります。 -Note that **error boundaries only catch errors in the components below them in the tree**. An error boundary can’t catch an error within itself. If an error boundary fails trying to render the error message, the error will propagate to the closest error boundary above it. This, too, is similar to how catch {} block works in JavaScript. +**error boundary は配下のツリー内のコンポーネントで発生したエラーのみをキャッチする**ことに注意してください。error boundary は自身で起こるエラーをキャッチできません。error boundary がエラーメッセージのレンダーに失敗した場合、そのエラーは最も近い上位の error boundary に伝搬します。この動作もまた、JavaScript の catch {} ブロックの動作と似ています。 -## Live Demo {#live-demo} +## ライブデモ {#live-demo} -Check out [this example of declaring and using an error boundary](https://codepen.io/gaearon/pen/wqvxGa?editors=0010) with [React 16](/blog/2017/09/26/react-v16.0.html). +[React 16](/blog/2017/09/26/react-v16.0.html) で [error boundary を宣言して利用する例](https://codepen.io/gaearon/pen/wqvxGa?editors=0010)を確認してください。 -## Where to Place Error Boundaries {#where-to-place-error-boundaries} +## error boundary を配置すべき場所 {#where-to-place-error-boundaries} -The granularity of error boundaries is up to you. You may wrap top-level route components to display a “Something went wrong” message to the user, just like server-side frameworks often handle crashes. You may also wrap individual widgets in an error boundary to protect them from crashing the rest of the application. +error boundary の粒度はあなた次第です。サーバサイドフレームワークがクラッシュを処理する際によく見られるように、最上位のルートコンポーネントをラップしてユーザーに “Something went wrong” メッセージを表示してもいいでしょう。各ウィジェットを個別にラップしてアプリケーションの残りの部分をクラッシュから守るのもいいでしょう。 -## New Behavior for Uncaught Errors {#new-behavior-for-uncaught-errors} +## エラーがキャッチされなかった場合の新しい動作 {#new-behavior-for-uncaught-errors} -This change has an important implication. **As of React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree.** +この変更には重要な意味があります。 **React 16 から、どの error boundary でもエラーがキャッチされなかった場合に React コンポーネントツリー全体がアンマウントされるようになりました。** -We debated this decision, but in our experience it is worse to leave corrupted UI in place than to completely remove it. For example, in a product like Messenger leaving the broken UI visible could lead to somebody sending a message to the wrong person. Similarly, it is worse for a payments app to display a wrong amount than to render nothing. +この決定については議論がありましたが、我々の経験上、壊れた UI をそのまま表示しておくことは、完全に削除してしまうよりももっと悪いことです。例えば、Messenger のような製品において壊れた UI を表示したままにしておくと、誰かが誤って別の人にメッセージを送ってしまう可能性があります。同様に、支払いアプリで間違った金額を表示することは、何も表示しないよりも悪いことです。 -This change means that as you migrate to React 16, you will likely uncover existing crashes in your application that have been unnoticed before. Adding error boundaries lets you provide better user experience when something goes wrong. +この変更のため、React 16 に移行すると、これまで気付かれていなかったアプリケーションの既存の不具合が明らかになることでしょう。error boundary を追加することで、問題が発生したときのユーザー体験を向上できます。 -For example, Facebook Messenger wraps content of the sidebar, the info panel, the conversation log, and the message input into separate error boundaries. If some component in one of these UI areas crashes, the rest of them remain interactive. +例えば、Facebook Messenger はサイドバー、情報パネル、会話ログ、メッセージ入力欄といったコンテンツを個別の error boundary でラップしています。これらの UI エリアの一部のコンポーネントがクラッシュしても、残りの部分はインタラクティブなままです。 -We also encourage you to use JS error reporting services (or build your own) so that you can learn about unhandled exceptions as they happen in production, and fix them. +また、本番環境で発生したキャッチされなかった例外について知って修正できるように、JS エラー報告サービスを利用(もしくは自身で構築)することもお勧めします。 -## Component Stack Traces {#component-stack-traces} +## コンポーネントのスタックトレース {#component-stack-traces} -React 16 prints all errors that occurred during rendering to the console in development, even if the application accidentally swallows them. In addition to the error message and the JavaScript stack, it also provides component stack traces. Now you can see where exactly in the component tree the failure has happened: +React 16 は開発時に、レンダー中に起こった全てのエラーをコンソールに出力します(アプリケーションが誤ってエラーを握り潰してしまっても出力します)。そこではエラーメッセージと JavaScript のスタックに加えて、コンポーネントのスタックトレースも提供します。これにより、コンポーネントツリーのどこでエラーが発生したのかが正確にわかります: Error caught by Error Boundary component -You can also see the filenames and line numbers in the component stack trace. This works by default in [Create React App](https://github.com/facebookincubator/create-react-app) projects: +コンポーネントスタックトレースにはファイル名と行番号も出力できます。[Create React App](https://github.com/facebookincubator/create-react-app) のプロジェクトではこれがデフォルトで有効になっています: Error caught by Error Boundary component with line numbers -If you don’t use Create React App, you can add [this plugin](https://www.npmjs.com/package/babel-plugin-transform-react-jsx-source) manually to your Babel configuration. Note that it’s intended only for development and **must be disabled in production**. +Create React App を使用しない場合は、[このプラグイン](https://www.npmjs.com/package/babel-plugin-transform-react-jsx-source)を手動で Babel の設定に追加してください。ただし、この機能は開発専用であり、**本番では必ず無効化しなければならない**ことに注意してください。 -> Note +> 補足 > -> Component names displayed in the stack traces depend on the [`Function.name`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name) property. If you support older browsers and devices which may not yet provide this natively (e.g. IE 11), consider including a `Function.name` polyfill in your bundled application, such as [`function.name-polyfill`](https://github.com/JamesMGreene/Function.name). Alternatively, you may explicitly set the [`displayName`](/docs/react-component.html#displayname) property on all your components. +> スタックトレースで表示されるコンポーネント名は [`Function.name`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name) プロパティに依存します。このプロパティをネイティブで提供しない古いブラウザやデバイス(IE 11 など)をサポートする場合は、アプリケーションバンドルに `Function.name` のポリフィル([`function.name-polyfill`](https://github.com/JamesMGreene/Function.name) など)を含めることを検討してください。もしくは、全てのコンポーネントに [`displayName`](/docs/react-component.html#displayname) プロパティを明示的に設定することもできます。 -## How About try/catch? {#how-about-trycatch} +## try/catch について {#how-about-trycatch} -`try` / `catch` is great but it only works for imperative code: +`try` / `catch` は素晴らしいですが、命令型のコードでのみ動作します: ```js try { @@ -116,21 +116,21 @@ try { } ``` -However, React components are declarative and specify *what* should be rendered: +一方、React コンポーネントは宣言型であり、*何が*レンダーされるべきなのかを指定します: ```js