Skip to main content
rule CX Codex

error-handling-recovery — Claude Code rule: WebGL, install

The error-handling-recovery rule covers WebGL context loss, resource rebuilding, and fallback UI. Use it when a Three.js scene must recover from graphics failures.

MIT ★ 4,719 updated 2026-10-24

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/rules/error-handling-recovery.md
Open on GitHub

What error-handling-recovery does

The rule adds handlers for webglcontextlost and webglcontextrestored. They stop the animation loop, display recovery feedback, rebuild the scene resources, and start rendering again. Its SceneManager pattern tracks resources that need recreation after the context returns.

It also includes a React Error Boundary for Three.js failures, renderer and GPU diagnostics, and memory checks for geometries and textures. Context loss can be tested through WEBGL_lose_context. The renderer fallback sequence tries WebGPU, then WebGL2, WebGL1, and a static image.

The rule calls for keeping scene state so resources can be rebuilt after recovery. Memory leaks, GPU overload, tab switching, driver problems, and GPU crashes are treated as possible causes of context loss.

What it helps with

  • handle a lost WebGL context
  • rebuild Three.js materials and textures
  • show recovery feedback for a failed 3D scene
  • monitor geometry and texture counts
  • add renderer and static-image fallbacks

Example prompts for the agent

  • Add WebGL context-loss recovery to my Three.js scene.
  • Rebuild the scene resources after webglcontextrestored.
  • Test the recovery path with WEBGL_lose_context and add a React error fallback.

How to install error-handling-recovery

Manually: put the files in place

.claude/rules/error-handling-recovery.md

The paths frontmatter field limits the files

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about error-handling-recovery

How do I install error-handling-recovery in Claude Code?

Place the rule file at .claude/rules/error-handling-recovery.md.

What does error-handling-recovery do?

It describes WebGL context-loss detection, resource recreation, render-loop recovery, React error handling, diagnostics, memory checks, and renderer fallbacks.

How can I test WebGL context recovery?

Get the WEBGL_lose_context extension, call loseContext(), then call restoreContext() after a delay to exercise the recovery path.

Source text

error-handling-recovery.md · MIT
# Error Handling & Context Recovery

Handling WebGL errors and context loss gracefully.

## WebGL Context Lost

```javascript
const canvas = renderer.domElement;

canvas.addEventListener('webglcontextlost', (event) => {
  event.preventDefault(); // Indicates we'll handle recovery
  console.warn('WebGL context lost');

  // Stop render loop
  cancelAnimationFrame(animationId);

  // Show error UI
  showErrorOverlay('Graphics context lost. Recovering...');
});

canvas.addEventListener('webglcontextrestored', () => {
  console.log('WebGL context restored');

  // Recreate resources
  initScene();
  initMaterials();
  initTextures();

  // Restart render loop
  animate();

  hideErrorOverlay();
});
```

## Common Causes of Context Loss

1. **Memory Leaks**: Not disposing resources
2. **GPU Overload**: Too many draw calls
3. **Browser Tab Switch**: Mobile browsers free memory
4. **Driver Issues**: Especially on Windows
5. **GPU Crash**: Hardware/driver failure

## Simulating Context Loss (Testing)

```javascript
const ext = renderer.getContext().getExtension('WEBGL_lose_context');

// Lose context
ext.loseContext();

// Restore after delay
setTimeout(() => ext.restoreContext(), 1000);
```

## Resource Recreation Pattern

```javascript
class SceneManager {
  constructor() {
    this.resources = [];
    this.setupContextHandlers();
  }

  setupContextHandlers() {
    const canvas = this.renderer.domElement;

    canvas.addEventListener('webglcontextlost', (e) => {
      e.preventDefault();
      this.onContextLost();
    });

    canvas.addEventListener('webglcontextrestored', () => {
      this.onContextRestored();
    });
  }

  registerResource(resource) {
    this.resources.push(resource);
  }

  onContextLost() {
    // Mark all resources as needing recreation
    this.resources.forEach(r => r.needsRecreation = true);
  }

  onContextRestored() {
    // Recreate all resources
    this.resources.forEach(r => {
      if (r.needsRecreation) {
        r.recreate();
        r.needsRecreation = false;
      }
    });
  }
}
```

## React Error Boundary

```jsx
class ThreeErrorBoundary extends React.Component {
  state = { hasError: false, error: null };

  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  componentDidCatch(error, info) {
    console.error('Three.js error:', error);
    // Report to error tracking service
    reportError(error, info);
  }

  retry = () => {
    this.setState({ hasError: false, error: null });
  };

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-fallback">
          <p>3D scene failed to load.</p>
          <button onClick={this.retry}>Retry</button>
        </div>
      );
    }
    return this.props.children;
  }
}

// Usage
<ThreeErrorBoundary>
  <Canvas>
    <Scene />
  </Canvas>
</ThreeErrorBoundary>
```

## Production Logging

```javascript
function logRendererInfo() {
  const gl = renderer.getContext();
  const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');

  const info = {
    vendor: gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL),
    renderer: gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL),
    maxTextureSize: gl.getParameter(gl.MAX_TEXTURE_SIZE),
    maxViewportDims: gl.getParameter(gl.MAX_VIEWPORT_DIMS),
    memory: renderer.info.memory,
    render: renderer.info.render
  };

  console.log('Renderer Info:', info);
  return info;
}

// Log on errors
window.addEventListener('error', (e) => {
  if (e.message.includes('WebGL') || e.message.includes('THREE')) {
    logRendererInfo();
  }
});
```

## Memory Monitoring

```javascript
function checkMemory() {
  const { geometries, textures } = renderer.info.memory;

  console.log(`Geometries: ${geometries}, Textures: ${textures}`);

  // Warning thresholds
  if (textures > 100) {
    console.warn('High texture count - check for leaks');
  }
  if (geometries > 500) {
    console.warn('High geometry count - check for leaks');
  }
}

// Check periodically
setInterval(checkMemory, 30000);
```

## Graceful Degradation

```javascript
function initRenderer() {
  // Try WebGPU first
  if (navigator.gpu) {
    try {
      return new THREE.WebGPURenderer({ antialias: true });
    } catch (e) {
      console.warn('WebGPU failed, falling back to WebGL');
    }
  }

  // Try WebGL2
  try {
    const canvas = document.createElement('canvas');
    if (canvas.getContext('webgl2')) {
      return new THREE.WebGLRenderer({ antialias: true });
    }
  } catch (e) {
    console.warn('WebGL2 failed, trying WebGL1');
  }

  // WebGL1 fallback
  try {
    return new THREE.WebGLRenderer({
      antialias: false,
      precision: 'mediump'
    });
  } catch (e) {
    // Show static image fallback
    showStaticFallback();
    return null;
  }
}
```

## Recovery Strategies

| Strategy | When to Use |
|----------|-------------|
| **Prevent** | Dispose aggressively, monitor memory |
| **Detect** | Listen for context lost events |
| **Recover** | Recreate resources from saved state |
| **Fallback** | Show static image or message |

## Best Practices

1. **Always Handle Context Loss**: Don't assume WebGL is always available

2. **Save State**: Keep track of scene state for recreation

3. **Dispose Properly**: Prevent context loss by managing memory

4. **User Feedback**: Show clear messages during recovery

5. **Logging**: Capture device info for debugging

6. **Fallbacks**: Have static fallback for critical content

## References

- [WebGL Context Lost](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/webglcontextlost_event)
- [Three.js dispose()](https://threejs.org/docs/#manual/en/introduction/How-to-dispose-of-objects)

© zebbern · MIT · zebbern/claude-code-guide

Similar IDE rules

All IDE rules for Frontend and UI →

From the same set86

The whole set →
physics-integration physics-integration guides Three.js integration with Rapier and Cannon-es: Vite setup, collider primitives, and mesh synchronization patterns. CX Codex +1 ★ 4,719repo stars raycasting-optimization The raycasting-optimization rule covers ways to reduce Three.js raycasting work, from filtering objects by layer to using BVH or GPU picking. Useful when a scene has complex meshes or frequent pointer checks. CX Codex +1 ★ 4,719repo stars mobile-optimization mobile-optimization is a rule for accelerating Three.js scenes on smartphones and tablets. It reduces GPU load and memory use, helping maintain a stable frame rate. CX Codex +1 ★ 4,719repo stars webxr-setup The webxr-setup rule for Claude Code guides building VR and AR scenes in Three.js WebXR. It helps coding agents set up render loops, controllers, and hit-testing. CX Codex +1 ★ 4,719repo stars vc-industry-research vc-industry-research turns a prompt into a PE/VC-style industry report: sector deep-dive, investment memo or market analysis, in Chinese or English, PDF by default. CX Codex +1 ★ 4,719repo stars tsl-complete-reference The tsl-complete-reference rule for Claude Code provides a TSL reference for writing node shaders without invalid syntax. CX Codex +1 ★ 4,719repo stars test-suite-architect test-suite-architect sets up QA infrastructure based on Google Testing Standards and OWASP: AAA test case templates, P0-P4 bug tracking, quality gate checks, and LLM test execution. CX Codex +1 ★ 4,719repo stars ssh-penetration-testing ssh-penetration-testing guides SSH service assessments, from configuration checks to credential testing and port forwarding. Use it to plan an authorized SSH security review. CX Codex +1 ★ 4,719repo stars

Project sponsors

Companies that keep this analytics open