frontend/containers/ErrorBoundary/index.js (view raw)
1import React, {Component} from 'react';
2import LogoutAndRedirect from './LogoutAndRedirect';
3import {ApiProblem} from 'strapi-react-context';
4import {Redirect} from 'react-router-dom';
5
6/**
7 * Error boundary to catch all the error from our code.
8 * If the error catched is an `unauthorized` APIProblem, will logout and redirect. Otherwise
9 * will redirect to an /error page. (nicer than blank page)
10 */
11class ErrorBoundary extends Component {
12 state = {error: null};
13
14 /**
15 * @param {Error} error
16 * @return {Object} new state after derivation
17 */
18 static getDerivedStateFromError(error) {
19 if (error instanceof ApiProblem) {
20 return {error: error.kind};
21 }
22 return {error: 'unknown'};
23 }
24
25 /**
26 * Component did catch an error, log it.
27 * @param {Error} error
28 */
29 componentDidCatch(error) {
30 console.error('App did catch an error', {error});
31 }
32
33 /**
34 * @override
35 */
36 render() {
37 if (this.state.error === null) return this.props.children;
38
39 if (this.state.error === 'unauthorized') return <LogoutAndRedirect />;
40 return <Redirect to="error" />;
41 }
42}
43export default ErrorBoundary;