Error Handling in React

Overview

Error handling in React helps prevent the app from crashing and improves user experience.

React doesn’t catch errors in event handlers or lifecycle methods with normal try-catch. Special mechanisms are required.

1. Error Boundaries

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree and display a fallback UI instead of crashing.

When to use them?

Wrap risky components: widgets, dashboards, charts, lazy-loaded components

Example:

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

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

  componentDidCatch(error, errorInfo) {
    console.error("Logged error:", error, errorInfo);
    // log error to service
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

Key Point:

  • Error boundaries only catch errors during rendering, lifecycle methods, and constructors in the component tree.

2. Handling Errors in Event Handlers

  • Error boundaries don’t catch errors in event handlers.
  • Use try...catch inside the function.
function Button() {
  const handleClick = () => {
    try {
      // risky logic
    } catch (error) {
      console.error("Caught in event:", error);
    }
  };

  return <button onClick={handleClick}>Click</button>;
}

Key Point:

  • Always use try...catch in event handlers and async functions.

3. Handling Async Errors

async function fetchData() {
  try {
    const response = await fetch('/api/data');
    const json = await response.json();
  } catch (err) {
    console.error("Async error:", err);
  }
}

Use try-catch for:

  • fetch() / API calls
  • File uploads
  • Database operations

4. Summary

What to Know

  • React error handling includes render-time errors, event handler errors, and async operation errors.
  • Use Error Boundaries to catch render and lifecycle errors.
  • Use try...catch for event handlers and async functions.

Error Types & Handling Methods

Error TypeHow to Handle
Render/Lifecycle errorsUse Error Boundaries (getDerivedStateFromError, componentDidCatch)
Event handler errorsUse try...catch inside the event handler
Async (API/fetch) errorsUse try...catch inside async functions
Form/UI-level validationUse local component state to show errors

Best Practices

PracticeWhy It Matters
Use Error BoundariesPrevent the entire app from crashing on render errors
Add try...catch in eventsCatch and gracefully handle user-triggered logic errors
Handle async errors properlyAvoid unhandled promise rejections in API calls
Show fallback UIImprove user experience with error messages or loaders
Log errors to external servicesHelps with debugging and monitoring in production

Bình luận

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *