main

mattermost/focalboard

Last updated at: 29/12/2023 09:40

error_boundary.tsx

TLDR

This file contains the implementation of an ErrorBoundary component that is used to catch and handle errors in other components.

Classes

ErrorBoundary

The ErrorBoundary component is a class component that wraps other components to catch and handle errors. It has the following properties:

State

  • hasError (boolean): Indicates whether an error has occurred.

Props

  • children (React.ReactNode): The children components to be rendered by the ErrorBoundary.

Methods

  • handleError: Handles the error caught by the ErrorBoundary by redirecting to an error page.
  • getDerivedStateFromError: A static method that gets called when an error is thrown inside the ErrorBoundary's children components. It updates the hasError state to true.
  • componentDidCatch: A lifecycle method that gets called when an error is caught by the ErrorBoundary. It logs the error and error information.
  • shouldComponentUpdate: A lifecycle method that determines whether the component should update or not.
  • render: Renders the ErrorBoundary component and its children. If an error has occurred, it redirects to an error page; otherwise, it renders the children components.
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

import React from 'react'

import {Utils} from '../../../webapp/src/utils'

type State = {
    hasError: boolean
}

type Props = {
    children: React.ReactNode
}

export default class ErrorBoundary extends React.Component<Props, State> {
    state = {hasError: false}
    msg = 'Redirecting to error page...'

    handleError = (): void => {
        const url = Utils.getBaseURL() + '/error?id=unknown'
        Utils.log('error boundary redirecting to ' + url)
        window.location.replace(url)
    }

    static getDerivedStateFromError(/*error: Error*/): State {
        return {hasError: true}
    }

    componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
        Utils.logError(error + ': ' + errorInfo)
    }

    shouldComponentUpdate(): boolean {
        return true
    }

    render(): React.ReactNode {
        if (this.state.hasError) {
            this.handleError()
            return <span>{this.msg}</span>
        }
        return this.props.children
    }
}