Why isn't componentDidCatch not working?

I am attempting to create a ‘fail whale’ page that pops up whenever the app crashes.

To do this I am attempting to use ‘error boundaries’ along with the new componentDidCatch lifecycle method. https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html

I am having no success so far and no matter what, the error crashes the app.

Here is the reproduction code:


import React, { Component } from 'react';
import { View, Text } from 'react-native';

class InnerComponent extends Component {
  render() {
    throw new Error('why isn\'t this working')
    return(
      <View>
        <Text>Why is this rendering?</Text>
      </View>
      )
  }
}

class ErrorBoundary extends Component {
    constructor(props) {
      super(props)
      this.state = { hasError: false }
    }

    componentDidCatch(error, info) {
      this.setState({ hasError: true })
      console.log(error, info)
    }

    render() {
      if (this.state.hasError) {
        return (
          <View>
            <Text>Why is this not rendering?</Text>
          </View>
        )
      }
      return this.props.children
    }
}

export default class App extends Component {
  render() {
    return (
      <ErrorBoundary>
        <InnerComponent/>
      </ErrorBoundary>
    );
  }
}

Here is a snack I made with the same issues: https://snack.expo.io/BynlDr6-z

What am I doing wrong here?

I posted this question on StackOverflow here: javascript - Why isn't componentDidCatch not preventing app crashes? - Stack Overflow?

One of the commenters has managed to get this to run on their local environment which is very odd. If Snack is using SDKv23 and thus React 16. Shouldn’t it be working correctly here?

Thanks!

Hey @judgejab

So I spent a significant amount of time testing this problem for you. And you are right, it doesn’t work within Snack. I made some adjustments to your snack where it works without the throw.

https://snack.expo.io/Hk1Zh2Tbz

However, If you create a new expo project, and you copy and paste this code in the Snack it should work!

npm install -g exp
exp init error-handler
cd error-handler
exp start

I’m sorry this must have been frustrating, let me know if I can help you in any other way.

Hey @jimmylee, thank you for taking a look at this.

I’m not sure why I’d want this without the throw keyword…that’s what I’m trying to catch in componentDidCatch.

Yeah I totally understand that, I’m just trying to let you know that it works outside of Snack, so if you need it to work within an Expo application I can verify it works.

You can get this code to work outside of Snack? Within Expo? WITH the throw? That would be amazing!

I’ve tried reproducing this several times with no luck L:frowning:

Hey @judgejab, componentDidCatch now works in snack starting with SDK 24. https://snack.expo.io/Byq_Q3SfG

1 Like