Galit Tugi
Galit Tugi

Reputation: 49

React 16 - error handling for event handlers

I'm migrating our application from react 15.4 to react 16. We're using react's new errorBonudries which is awesome, but it has a major issue - events and asynchronous actions are not catched by the error boundaries, and I need to catch and log them.

The workaround I found was usign window.onerror, but looks like react "swallows" the real error details as no real data about the error is sent to the event.

Are there any suggestions for this type of handling which do not include using try/catch to every event block we're writing?

Thanks!

Upvotes: 3

Views: 3482

Answers (1)

Sagiv b.g
Sagiv b.g

Reputation: 31024

Are there any suggestions for this type of handling which do not include using try/catch to every event block we're writing?

In short, No. You must use try/catch blocks.

This is due to the simple fact that event handlers (and other async operations) are asynchronous, they do not run on the same iteration of the event loop as the render of the error boundary.
So trying to achieve what your asking here is as if you wrote something like this:

try {
  setTimeout(() => {
    throw new Error('my error outside the event loop')
  }, 0)
} catch (err) {
  console.log('error catched!', err)
}

So you need to sync the render and the async operation (event handler in this case), one way to do it is with setState and try/catch block.
You try the code and on catch you store the error in state, this will cause a re-render and then you can conditionally render the error or listen to this change and log something. but this approach is far from being convenient.

Upvotes: 2

Related Questions