Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Translate Error Boundaries #81

Merged
merged 7 commits into from
Feb 13, 2019
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 44 additions & 43 deletions content/docs/error-boundaries.md
Original file line number Diff line number Diff line change
@@ -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` のコールバック)
> * サーバーサイドレンダリング
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ここだけレンダリングを残しました

> * (子コンポーネントではなく)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 {
Expand Down Expand Up @@ -52,61 +52,62 @@ class ErrorBoundary extends React.Component {
}
```

Then you can use it as a regular component:
使用する際は通常のコンポーネントとして扱います:

```js
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>
```

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 のスタックに加えて、コンポーネントのスタックトレースも提供します。これにより、コンポーネントツリーのどこでエラーが発生したのかが正確にわかります:

<img src="../images/docs/error-boundaries-stack-trace.png" style="max-width:100%" alt="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) のプロジェクトではこれがデフォルトで有効になっています:

<img src="../images/docs/error-boundaries-stack-trace-line-numbers.png" style="max-width:100%" alt="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 の設定に追加してください。
ただし、この機能は開発専用であり、**本番では必ず無効化しなければならない**ことに注意してください。
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

原文にはない改行があるので、削除お願いします 🙏


> 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 {
Expand All @@ -116,21 +117,21 @@ try {
}
```

However, React components are declarative and specify *what* should be rendered:
一方、React コンポーネントは宣言型であり、*何が*レンダリングされるべきなのかを指定します:

```js
<Button />
```

Error boundaries preserve the declarative nature of React, and behave as you would expect. For example, even if an error occurs in a `componentDidUpdate` method caused by a `setState` somewhere deep in the tree, it will still correctly propagate to the closest error boundary.
Error Boundary は React の宣言型という性質を保持しつつ、期待通りの動作をします。例えば、`componentDidUpdate` メソッドで発生したエラーがツリー内のどこか深い場所にある `setState` によって引き起こされていた場合でも、最も近い Error Boundary にそのことが正しく伝播します。

## How About Event Handlers? {#how-about-event-handlers}
## イベントハンドラについて {#how-about-event-handlers}

Error boundaries **do not** catch errors inside event handlers.
Error Boundary はイベントハンドラ内で発生したエラーをキャッチ**しません**。

React doesn't need error boundaries to recover from errors in event handlers. Unlike the render method and lifecycle methods, the event handlers don't happen during rendering. So if they throw, React still knows what to display on the screen.
イベントハンドラ内のエラーから回復するのに Error Boundary は不要です。レンダリングメソッドやライフサイクルメソッドとは異なり、イベントハンドラはレンダリング中には実行されません。そのためイベントハンドラ内でエラーが発生しても、React が画面に表示する内容は変わりません。

If you need to catch an error inside event handler, use the regular JavaScript `try` / `catch` statement:
イベントハンドラ内のエラーをキャッチする必要がある場合は、普通の JavaScript `try` / `catch` 文を使用してください:

```js{9-13,17-20}
class MyComponent extends React.Component {
Expand All @@ -157,10 +158,10 @@ class MyComponent extends React.Component {
}
```

Note that the above example is demonstrating regular JavaScript behavior and doesn't use error boundaries.
上記の例では、標準の JavaScript を使用して Error Boundary を使用していないことに注目してください。

## Naming Changes from React 15 {#naming-changes-from-react-15}
## React 15からの命名の変更 {#naming-changes-from-react-15}

React 15 included a very limited support for error boundaries under a different method name: `unstable_handleError`. This method no longer works, and you will need to change it to `componentDidCatch` in your code starting from the first 16 beta release.
React 15 は Error Boundary を異なるメソッド名(`unstable_handleError`)で非常に限定的にサポートしていました。このメソッドはもう動作しないため、16ベータ版リリース以降はコードを `componentDidCatch` に変更する必要があります。

For this change, we’ve provided a [codemod](https://github.com/reactjs/react-codemod#error-boundaries) to automatically migrate your code.
この変更について、自動的にコードを移行できる [codemod](https://github.com/reactjs/react-codemod#error-boundaries) が提供されています。