Blog>
Snippets

Logging Errors to an External Service

Extend an Error Boundary to catch errors and log them to an external monitoring or logging service.
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

function logErrorToMyService(error, errorInfo) {
  // Replace with your own error logging service URL or setup
  const logServiceUrl = 'https://your-error-logging-service.com/log';
  
  // Send error details to the logging service
  fetch(logServiceUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      error: error.toString(),
      errorInfo: errorInfo.componentStack
    })
  })
    .then(response => response.json())
    .catch(err => console.error('Failed to log error:', err));
}

// Usage example:
// <ErrorBoundary>
//   <YourComponent />
// </ErrorBoundary>
This code snippet shows a React Component called ErrorBoundary, which can wrap child components to catch JavaScript errors anywhere in the child component tree. When an error occurs, it logs the error and potentially the component stack to an external error logging service using the logErrorToMyService function. This function does a POST request to send the error details to your specified logging service. Upon catching an error, the boundary also sets a state flag (`hasError`) to display a fallback UI.