admin管理员组文章数量:1303374
Apologies, I know this has been asked, but I can't find a single example that works for me. Seems like it's not easy enough to understand if so many are struggling with it.
I just need to know how to catch errors in React in a clean, simple way. I'm using CRA 2.0/React 16.7. I want a try/catch block at the action level, as this is where business logic is concentrated in my app.
I read this and implemented it as described, but my ErrorBoundary object never catches errors.
Example:
import React, { Component } from "react";
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
ponentDidCatch(error, info) {
console.log("ErrorBoundary: ", error);
console.log("ErrorBoundary: ", info);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
I'm wrapping my routes at the top level:
return (
<BrowserRouter>
<ErrorBoundary>
<div className="main-container">
<SideBar />
<div className="some-class">
<Switch>
<Route path="/events" ponent={Events} />
<Route exact path="/" ponent={Index} />
</Switch>
</div>
</div>
</ErrorBoundary>
</BrowserRouter>
);
In "events" above, I make an API call which is throwing a 500 error on the API side:
ponentDidMount() {
this.props.getAllEvents();
}
Here's the Redux action:
export const getAllEvents = () => {
return async (dispatch, getState) => {
try {
let state = getState();
const result = await get({
state: state,
route: "/v1/events"
});
dispatch({
type: GET_EVENTS,
payload: result
});
} catch (e) {
console.log("Something went wrong at action...");
}
};
};
..."get()" is just wrapping an Axios GET - nothing fancy.
I see a 500 error in the console from the failed API call. I never see the "Something went wrong..." in the console, from the catch block above, though that line does get hit while debugging.
The "ponentDidCatch()" method never gets called - "hasError" is always false and it always renders the children.
If I remove the throw block in the API endpoint, everything works fine and I get my data. I'm just not able to catch errors at the UI level. I've tried a try/catch in the "ponentDidMount()", I've tried removing the try/catch block in the action...behavior doesn't change.
Thanks in advance.
Apologies, I know this has been asked, but I can't find a single example that works for me. Seems like it's not easy enough to understand if so many are struggling with it.
I just need to know how to catch errors in React in a clean, simple way. I'm using CRA 2.0/React 16.7. I want a try/catch block at the action level, as this is where business logic is concentrated in my app.
I read this and implemented it as described, but my ErrorBoundary object never catches errors.
Example:
import React, { Component } from "react";
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
ponentDidCatch(error, info) {
console.log("ErrorBoundary: ", error);
console.log("ErrorBoundary: ", info);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
I'm wrapping my routes at the top level:
return (
<BrowserRouter>
<ErrorBoundary>
<div className="main-container">
<SideBar />
<div className="some-class">
<Switch>
<Route path="/events" ponent={Events} />
<Route exact path="/" ponent={Index} />
</Switch>
</div>
</div>
</ErrorBoundary>
</BrowserRouter>
);
In "events" above, I make an API call which is throwing a 500 error on the API side:
ponentDidMount() {
this.props.getAllEvents();
}
Here's the Redux action:
export const getAllEvents = () => {
return async (dispatch, getState) => {
try {
let state = getState();
const result = await get({
state: state,
route: "/v1/events"
});
dispatch({
type: GET_EVENTS,
payload: result
});
} catch (e) {
console.log("Something went wrong at action...");
}
};
};
..."get()" is just wrapping an Axios GET - nothing fancy.
I see a 500 error in the console from the failed API call. I never see the "Something went wrong..." in the console, from the catch block above, though that line does get hit while debugging.
The "ponentDidCatch()" method never gets called - "hasError" is always false and it always renders the children.
If I remove the throw block in the API endpoint, everything works fine and I get my data. I'm just not able to catch errors at the UI level. I've tried a try/catch in the "ponentDidMount()", I've tried removing the try/catch block in the action...behavior doesn't change.
Thanks in advance.
Share Improve this question asked Feb 23, 2019 at 14:46 Tsar BombaTsar Bomba 1,1066 gold badges31 silver badges64 bronze badges2 Answers
Reset to default 6As the other answer correctly stated, React error boundary will only catch rendering errors.
Since you are using redux, you could build your own mechanism for cases like yours:
- Whenever an error occurs, you dispatch an action with an
error
property. - A reducer only looks for actions that has
error
property. It receives the action and update a "global error" state in your state tree - An app-wide
connect
ed wrapper ponent sees this change in state and displays fallback UI.
For example:
Dispatch an action with error
property:
export const getAllEvents = () => {
return async (dispatch, getState) => {
try {
...
} catch (e) {
dispatch({
type: ERROR,
error: e // dispatch an action that has `error` property
});
}
};
};
A reducer sees it and update the state.error
part:
export default function errorReducer(state = null, action) {
const { type, error } = action;
if (type === RESET_ERROR_MESSAGE) { // an action to clear the error
return null;
} else if (error) { // any type of action, but contains an `error`
return error;
}
return state;
}
Now you wrap your app in a connected
boundary:
function Wrapper({error}) {
if(error) return <h1>Something went wrong</h1>;
return <App/>;
}
export default connect(
state => ({
error: state.error,
})
)(Wrapper);
From the React Error Boundaries docs:
Error boundaries do not catch errors for:
- Event handlers (learn more)
- Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)
- Server side rendering
- Errors thrown in the error boundary itself (rather than its children)
本文标签: javascriptReact ErrorBoundaryJust can39t get it to workStack Overflow
版权声明:本文标题:javascript - React ErrorBoundary - Just can't get it to work - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741729199a2394762.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论