Yes, but only if the failure occurs during the rendering phase. In a standard implementation using React.lazy and Suspense, a network failure during a chunk fetch results in a rejected Promise. Because Error Boundaries only catch errors during the render phase, lifecycle methods, and constructors, they will intercept the error thrown by the React.lazy component when it attempts to resolve that failed Promise during render.
How Chunk Failures Interact with Boundaries
When a browser fails to fetch a JavaScript chunk (e.g., a 404 error after a new deployment has deleted old assets), the import() call returns a rejected Promise. React.lazy is designed to throw this rejection as an error during the component's rendering attempt. If the Suspense component is wrapped in an Error Boundary, that boundary will catch the resulting error and display the fallback UI.
Confirmed Behavior vs. Common Misconceptions
- Confirmed: An Error Boundary wrapping a
Suspense block will catch the error thrown by a failed React.lazy load.
- Misconception: Some developers believe this is an "asynchronous error" (like a
setTimeout or an API call) that bypasses boundaries. While the fetch is asynchronous, the error manifestation happens during React's render cycle, making it catchable.
- Limitation: The Error Boundary catches the error, but it does not automatically "retry" the fetch. The application remains in the error state until a page reload or a manual state reset occurs.
Implementation for Logging and Recovery
To capture these failures for external logging services (like Sentry or LogRocket) and provide a recovery path, use the componentDidCatch lifecycle method:
class ChunkErrorBoundary extends React.Component {
componentDidCatch(error, errorInfo) {
// Log to external service
logErrorToService(error, errorInfo);
// Optional: Detect if it is a ChunkLoadError to suggest a reload
if (error.name === 'ChunkLoadError' || error.message.includes('Loading chunk')) {
console.error('Asset mismatch detected. Suggesting page refresh.');
}
}
render() {
if (this.state.hasError) {
return <div>Something went wrong. Please refresh the page.</div>;
}
return this.props.children;
}
}
Verification Steps
- Deploy the application to a production-like environment.
- Open the application in a browser.
- Manually delete or rename a JS chunk file on the server (or use Chrome DevTools Network tab to block the specific chunk URL).
- Navigate to the route that triggers the
React.lazy load.
- Verify that the Error Boundary fallback renders instead of a blank screen or a silent console error.
Diagnostic Detail Required: Are you using a custom wrapper around import() or a third-party routing library (like React Router's lazy) that might be intercepting promise rejections before they reach the React render cycle?