You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/docs/error-boundaries.md
+36-1Lines changed: 36 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -13,6 +13,13 @@ A JavaScript error in a part of the UI shouldn’t break the whole app. To solve
13
13
14
14
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.
15
15
16
+
> Note
17
+
>
18
+
> Error boundaries do **NOT** work in the following scenarios:
19
+
> * Event Handlers (See below ["How About Try / Catch"](#how-about-trycatch) for details about dealing with errors in event handlers)
20
+
> * Asynchronous code (e.g. `setTimeout` or `requestAnimationFrame` callbacks)
21
+
> * Server Side Rendering
22
+
16
23
A class component becomes an error boundary if it defines a new lifecycle method called `componentDidCatch(error, info)`:
17
24
18
25
```js{7-12,15-18}
@@ -109,7 +116,7 @@ You can also see the filenames and line numbers in the component stack trace. Th
109
116
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**.
110
117
111
118
112
-
## Why Not Use try/catch?
119
+
## How About try/catch?
113
120
114
121
`try` / `catch` is great but it only works for imperative code:
115
122
@@ -129,6 +136,34 @@ However, React components are declarative and specify *what* should be rendered:
129
136
130
137
Error boundaries preserve the declarative nature of React, and behave as you would expect. For example, even if an error occurs in a `componentDidUpdate` hook caused by a `setState` somewhere deep in the tree, it will still correctly propagate to the closest error boundary.
131
138
139
+
However, an event handler inside of a React component could leverage `try` / `catch` to deal with errors that occur during event handling.
140
+
141
+
```js{8-12,16-19}
142
+
class MyComponent extends React.Component {
143
+
constructor(props) {
144
+
super(props);
145
+
this.state = { error: null }
146
+
}
147
+
148
+
handleClick = () => {
149
+
try {
150
+
// event handling that could possibly produces an error
151
+
} catch(error) {
152
+
this.setState({ error })
153
+
}
154
+
}
155
+
156
+
render() {
157
+
if (this.state.error) {
158
+
// render a fallback UI
159
+
return <h1>The Click Handler Produces an Error</h1>
0 commit comments