Logging Errors from Boundaries
What you'll learn: How to send error details from error boundaries to external logging services so you can track and fix production issues while users see a friendly fallback UI.
When an error boundary catches a component error, you have two jobs: show users a graceful fallback UI and capture the error details for your development team. Error boundaries are your production safety net—but they're only useful if you know what errors they're catching.
Why Log from Boundaries?
Think of error boundaries as security cameras in a store. They prevent disasters (crashes) from affecting customers, but the footage (error logs) tells you what went wrong so you can prevent it next time. Without logging, you're catching errors blindly.
Logging in componentDidCatch
The componentDidCatch(error, errorInfo) lifecycle method receives both the actual error and metadata about where it occurred. This is your opportunity to send that data to a logging service:
componentDidCatch(error, errorInfo) {
// Send to logging service
logErrorToService({
message: error.message,
stack: error.stack,
componentStack: errorInfo.componentStack,
timestamp: new Date().toISOString()
});
}
What to Log
Capture the error message, stack trace, component stack (which component tree failed), user context (if available), and timestamp. This helps you reproduce and fix the issue later.
Common Logging Services
You might send errors to services like Sentry, LogRocket, or your own backend endpoint. The boundary catches the error, prevents the crash, shows fallback UI, and quietly reports the problem—all without blocking the user.
Key Takeaway: Error boundaries should always log caught errors to external services using componentDidCatch, giving you visibility into production issues while maintaining a smooth user experience.