react-error-boundary catches error, but app crashes anyway

617 Views Asked by At

I have a view that contains a buggy component that I want to gracefully catch using react-error-boundary. The error is detected all right by react-error-boundary and the error handler renders its contents instead of those of the buggy component, but the app crashes anyway.

I have this in ErrorHandling.js:

class ErrorHandling {

  myErrorHandler = (error, info) => {
    // Do something with the error
    // E.g. log to an error logging client here
    console.log(`Error: ${error}. Info:`)
    console.log(info)
  }

  ErrorFallback = ({error, resetErrorBoundary}) => {
    return (
      <>
        <p>Something went wrong:</p>
        <pre>{error.message}</pre>
        <button onClick={resetErrorBoundary}>Try again</button>
      </>
    )
  }

}

export default new ErrorHandling()

This in BuggyComponent.js:

import { Card, CardBody } from 'reactstrap'
import { useEffect } from 'react'

const BuggyComponent = () => {

  useEffect(() => {
    throw new Error('This is an error')
  }, [])

  return (
    <Card className='text-center'>
      <CardBody>
        <p>This shouldn't show</p>
      </CardBody>
    </Card>
  )
}

export default BuggyComponent

This is my view:

import { Fragment } from 'react'
import { Row, Col } from 'reactstrap'
import BuggyComponent from '../componentes/auxiliares/BuggyComponent'
import {ErrorBoundary} from 'react-error-boundary'
import ErrorHandling from '../componentes/auxiliares/ErrorHandling'

const TestView = () => {
  return (
    <Fragment>
      <Row className='match-height'>
        <Col sm='12'>
          <ErrorBoundary 
            FallbackComponent={ErrorHandling.ErrorFallback} 
            // onError={ErrorHandling.myErrorHandler} 
            // onReset={() => {
            //   // reset the state of the app
            // }}
          >
            <BuggyComponent />
          </ErrorBoundary>
        </Col>
      </Row>
    </Fragment>
  )
}
export default TestView

And this is the error I get, at the right. The app crashes and I can't interact with it anymore. App crashes

1

There are 1 best solutions below

0
On

ErrorHandling.ErrorFallback is undefined. You either need to instantiate an ErrorHandling instance, or make ErrorFallback static:

class ErrorHandling {

  static myErrorHandler = (error, info) => {
    // Do something with the error
    // E.g. log to an error logging client here
    console.log(`Error: ${error}. Info:`)
    console.log(info)
  }

  static ErrorFallback = ({error, resetErrorBoundary}) => {
    return (
      <>
        <p>Something went wrong:</p>
        <pre>{error.message}</pre>
        <button onClick={resetErrorBoundary}>Try again</button>
      </>
    )
  }
}