Error Handler
Catches errors so one bug doesn’t freeze the game: records them, keeps the game loop running, shows a friendly message with a reload button if things keep failing, and lets tests read the list.
Files: error-handler.js (the component, no dependencies) and error-handler.test.mjs (4 tests).
Copy error-handler.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { createErrorHandler } from "./error-handler.js";
const errors = createErrorHandler({ onFatal: () => errors.showOverlay(document.body) });
errors.install(); // window errors and rejected promises
const safeFrame = errors.guard(frame, "frame"); // a throwing frame is recorded; after 5 in a row onFatal runs
requestAnimationFrame(function loop(t) { safeFrame(t); requestAnimationFrame(loop); });
// tests and the quality gates read window.__gameErrors
API
createErrorHandler({ target, onError, onFatal, maxErrors, fatalAfter, ignore, expose }) → errorserrors.install() / errors.uninstall()errors.capture(error, where) → the record { message, where, stack, count, first, last }errors.guard(fn, where) → a wrapped function that never throws; repeated failures in a row call onFatal onceerrors.list() → records (same message and place are merged, with a count)errors.clear()errors.showOverlay(container, { title, text, button })plain HTML message with a Reload button
ignore: array of strings or RegExps for noise (browser extensions, “ResizeObserver loop”)
expose: true (default) puts the list on globalThis.__gameErrors for automated checks
Engines
| Engine | Notes |
|---|---|
| Vanilla, Phaser, PixiJS, Three.js | yes. Wrap your own update / draw or the engine’s step callback with guard(). |
Tests
Node tests: capture and merging, ignore rules, guard keeps going then calls onFatal once, a good frame resets the count, window error and unhandledrejection events, exposure for tests, uninstall.
Run them with node --test toolkit/components/error-handler/ (Node 20 or newer, nothing to install).