Full Stack Development

Error Boundaries

by Tomas Trescak t.trescak@westernsydney.edu.au

Error Boundaries

/

Introduction

      import React, { render } from 'react';

function BuggyComponent() {
  throw new Error("Something went wrong!");
  return <div>Will never render</div>;
}

function App() {
  return <div>
    <BuggyComponent />
  </div>
}

render(<App />)
    

Error Boundaries

Introduction

    import React from 'react';


function App() {
  return (
    <>
      { 
        try {
           return <BuggyComponent />
        } catch (e) { }
      }
    </>
  )
} 

render(<App />)
  
/src/app/page.tsx

Error Boundaries

/

Introduction

  • Error Boundaries catch render-phase errors.
  • Must be class components.
  • Only catch render and lifecycle errors.
    function App() {
    <ErrorBoundary>
        <WreakHavoc />
    </ErrorBoundary>
}
  
    class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.error("Error caught by boundary:", error, errorInfo);
  }

  render() { //... }
}
  
    function BuggyComponent() {
  // will be caught
  throw new Error("Something went wrong!");

  setTimeout(() => {
    // will NOT be caught
    throw new Error("Something went wrong!");
  }, 100);

  // will not be caught
  async function futuro () {
    await wait(1);
    // will NOT bew caught
    throw new Error("Something went wrong!");
  }
  futuro();
}
  

Error Boundaries

/

How to Create

      class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {
    console.error(
      "Caught by boundary:", error, errorInfo
    );
  }

  render() {
    if (this.state.hasError) {
      return (
        <div>
          <h1>Oh bugger!</h1>
          <pre>
            {this.state.error.message}
          </pre>
        </div>
      )
    }
    return this.props.children;
  }
}

import { render } from 'react';

function BuggyComponent() {
  throw new Error("Something went wrong!");
  return <div>Never</div>;  
}

function App() {
  return (
    <ErrorBoundary>
      <BuggyComponent />
    </ErrorBoundary>
  )
}

render(<App />)