jonicious jonicious - 1 year ago 83
React JSX Question

How do I add general error handling into my React app?

I am currently building a React app which does a lot of server communication. If a server error occurs, I want to display the error to the user in a general way, e.g. an overlay with the error message.

Using container components

In my reducers, I return something like this:

loading: false,
error: {
msg: "An error occurred"

Obviously, my container components are redux aware. In the
function, I could check, if the current state has a property
and if so, I would render the error message. Oddly, in every container component, I would have to check the current state and might have duplicated code in every container component.

A more general approach

What am I looking for is a more general approach. Something that knows about all the states and displays the error message automatically if the current state contains an error. Think of it like an interceptor for errors. Of course, this component would not belong to a route, so I am wondering if this is even possible?

How do you do error handling in your React app? I would love to know your approach!

Answer Source

In my app, I've a action called handleError which will trigger a toast component in my app.

You can dispatch this action at the time of error. Like, you can dispatch it in the .catch() of the Promise.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download