ErrorBoundary.tsx 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /*
  2. * @Author: code4eat awesomedema@gmail.com
  3. * @Date: 2024-12-11 11:07:41
  4. * @LastEditors: code4eat awesomedema@gmail.com
  5. * @LastEditTime: 2024-12-11 11:08:26
  6. * @FilePath: /KC-MiddlePlatform/src/pages/login/ErrorBoundary.tsx
  7. * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
  8. */
  9. import React from 'react';
  10. interface ErrorBoundaryState {
  11. hasError: boolean;
  12. error: Error | null;
  13. errorInfo: React.ErrorInfo | null;
  14. }
  15. export class ErrorBoundary extends React.Component<{}, ErrorBoundaryState> {
  16. constructor(props: {}) {
  17. super(props);
  18. this.state = { hasError: false, error: null, errorInfo: null };
  19. }
  20. static getDerivedStateFromError(error: Error) {
  21. // 当子组件抛出错误时更新 state,用于 fallback UI 的显示
  22. return { hasError: true, error: error };
  23. }
  24. componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
  25. // 这里可以将错误信息上报到日志分析服务
  26. console.error('ErrorBoundary caught an error:', error, errorInfo);
  27. }
  28. render() {
  29. if (this.state.hasError) {
  30. // 这里展示一个简短的 fallback UI
  31. return <div>很抱歉,页面加载出现错误。</div>;
  32. }
  33. return this.props.children;
  34. }
  35. }