Quick answer: They catch different things, so register both. The window error event (window.onerror) fires for exceptions thrown synchronously in event handlers, timers and requestAnimationFrame callbacks. unhandledrejection fires for promise rejections nobody caught, which includes every exception inside an async function. Use addEventListener for both, add the capture flag to the error listener to see failed asset loads, and deduplicate before you send anything.
A browser game fails quietly. An exception in your update loop does not show a dialog. It stops the frame, writes a red line to a console nobody has open, and the player is left looking at a frozen canvas or a game that half works. JavaScript gives you two global hooks for hearing about it, window.onerror and unhandledrejection, and it is common to wire up one, see reports arrive, and assume the job is done. This guide covers what each one catches in an HTML5 game, the failures that get past both, and a complete handler that sends everything to a server.
- window.onerror and the error event
- unhandledrejection: promises and async functions
- Which listener catches what
- Failed asset loads do not bubble
- “Script error.” and cross-origin scripts
- Errors inside a requestAnimationFrame loop
- A complete handler for the error event and unhandledrejection
- Things that go wrong without throwing
- Noise, minified stacks and source maps
- Sending the report: fetch keepalive, sendBeacon and iframes
- What the Bugnet Web SDK installs
- Related guides
- Frequently asked questions
window.onerror and the error event
The older form is a property that holds one function with five arguments:
window.onerror = function (message, source, lineno, colno, error) { ... };
The modern form is an event listener that receives an ErrorEvent carrying the same data as properties:
window.addEventListener("error", function (event) {
// event.message, event.filename, event.lineno, event.colno, event.error
});
event.error is the thrown value, normally an Error with a name, a message and a stack. The stack is the valuable part.
Prefer addEventListener. Only one function can live in window.onerror, and engine loaders, analytics snippets and ad SDKs like to assign it. Whoever assigns last wins, and the others go silent. Listeners do not replace each other.
This event fires for exceptions that reach the top of a synchronous call stack: code in an input handler, a setTimeout or setInterval callback, a requestAnimationFrame callback, or the top level of a script.
unhandledrejection: promises and async functions
An exception thrown inside an async function does not travel up the call stack. It rejects the promise the function returned. If nothing awaits that promise or attaches a catch, the browser fires a different event:
window.addEventListener("unhandledrejection", function (event) {
// event.reason is whatever the promise rejected with
});
Modern game code is full of promises: asset loading with fetch, audio.play(), dynamic imports, save data in IndexedDB, WebAssembly instantiation, any async function loadLevel(). None of their failures reach window.onerror.
event.reason is not guaranteed to be an Error. It can be a string, undefined, or a DOMException such as the NotAllowedError that audio.play() rejects with when the player has not interacted with the page yet. Check before reading .stack.
Which listener catches what
| Failure | error | unhandledrejection |
|---|---|---|
Exception in an input handler, timer or requestAnimationFrame callback | Yes | No |
| Exception at the top level of a script | Yes | No |
Exception inside an async function or a .then() callback | No | Yes |
fetch() that rejects and is never caught | No | Yes |
<script> or <img> in the page that fails to load | Only in the capture phase | No |
new Image() or new Audio() created in code that fails to load | No | No |
| WebGL context lost | No | No |
The last three rows are where reporters built from a quick search fall short.
Failed asset loads do not bubble
When a <script>, <img> or <audio> element fails to load, the browser fires an error event at that element. It is a plain Event, not an ErrorEvent, and it does not bubble, so a normal listener on window never sees it. A listener registered for the capture phase does, because capture runs from the window down to the target:
window.addEventListener("error", handler, true); // third argument: capture
Inside the handler, tell the two kinds apart with event instanceof ErrorEvent. For a load failure, event.target is the element and its src or href is the file that failed.
There is a limit that matters for games. Capture only walks through the element’s ancestors in the document. An image created with new Image() and never added to the page has no ancestors, so its error event goes nowhere. Most asset loaders work exactly that way. For those, the failure has to be handled where the asset is requested: set img.onerror in your loader, and for fetch check response.ok, because a 404 resolves normally and only a network failure rejects. Engines such as Phaser and PixiJS expose their own loader error events for the same reason.
“Script error.” and cross-origin scripts
If your reports contain the message Script error. with no file, line or stack, the script that threw was loaded from a different origin than the page, without CORS. The browser hides the details so one site cannot read another site’s code through error messages. This shows up when the game bundle is on a CDN or a storage bucket while the HTML is served from your own domain.
The fix has two halves, and both are required:
<script src="https://cdn.example.com/game.js" crossorigin="anonymous"></script>
and the server that hosts game.js must send Access-Control-Allow-Origin: * or your page’s origin. With the attribute but without the header, the script does not load at all, so test after changing either side. Scripts loaded from the same origin as the page, which is the usual setup for a game zip uploaded to a portal, are not affected.
Errors inside a requestAnimationFrame loop
Where you schedule the next frame decides what the player experiences after an exception.
// A: schedule last. One error, then the loop is dead.
function frame(time) {
update(time);
render();
requestAnimationFrame(frame);
}
// B: schedule first. The loop survives and the error repeats.
function frame(time) {
requestAnimationFrame(frame);
update(time);
render();
}
In shape A, an exception in update means the last line never runs. You get one error event and the game freezes on its final frame while the page stays responsive. Players describe this as “the game froze”, never as an error. In shape B the loop keeps going and the same exception fires up to 60 times a second on a normal display, more on a fast one. The game may limp along, and your reporter gets flooded unless it deduplicates.
B plus deduplication is the better default: a broken enemy update is more playable than a dead canvas. If some errors really are fatal, catch them in the frame function and show your own message instead of leaving a frozen screen.
A complete handler for the error event and unhandledrejection
Put this in a script tag before your game code so it is listening when everything else loads. It sends JSON to a report endpoint. The URL, header and fields are Bugnet’s public submit API, and the same structure works for an endpoint of your own.
(function () {
"use strict";
var ENDPOINT = "https://api.bugnet.io/api/bugs/submit";
var API_KEY = "sk_live_your_project_key";
var GAME_VERSION = "1.0.3";
var MAX_REPORTS = 20;
var seen = new Set();
// Not your bugs: a harmless layout warning and browser extensions.
var NOISE = [
/^ResizeObserver loop/,
/(chrome|moz|safari-web)-extension:\/\//
];
function report(title, detail, category) {
title = String(title).slice(0, 200);
detail = String(detail);
if (seen.has(title) || seen.size >= MAX_REPORTS) return;
for (var i = 0; i < NOISE.length; i++) {
if (NOISE[i].test(title) || NOISE[i].test(detail)) return;
}
seen.add(title);
fetch(ENDPOINT, {
method: "POST",
keepalive: true,
headers: { "Content-Type": "application/json", "X-API-Key": API_KEY },
body: JSON.stringify({
title: title,
description: detail.slice(0, 20000),
category: category || "crash",
priority: category === "other" ? "medium" : "high",
platform: "Web",
game_version: GAME_VERSION,
os_info: navigator.userAgent.slice(0, 100),
device_info: (screen.width + "x" + screen.height + " @" +
window.devicePixelRatio + "x, host " + location.hostname).slice(0, 200),
auto_captured: true
})
}).catch(function () {});
}
function fileName(url) {
return String(url || "").split("?")[0].split("/").pop() || "inline";
}
// Capture phase: receives script errors and failed loads of elements
// that are in the document.
window.addEventListener("error", function (event) {
if (event instanceof ErrorEvent) {
if (event.message === "Script error." && !event.filename) {
report("Script error. (cross-origin script without CORS)",
"The browser withheld the details. Add crossorigin and CORS headers.");
return;
}
var err = event.error;
var name = err && err.name ? err.name : "Error";
var where = fileName(event.filename) + ":" + event.lineno + ":" + event.colno;
report(name + " at " + where,
event.message + "\n\n" + (err && err.stack ? err.stack : where));
return;
}
var el = event.target;
if (el && el !== window && el.tagName) {
var src = el.src || el.href || "";
report("Failed to load " + el.tagName.toLowerCase() + " " + fileName(src),
"Resource failed to load: " + src, "other");
}
}, true);
window.addEventListener("unhandledrejection", function (event) {
var reason = event.reason;
var isError = reason instanceof Error;
var name = isError ? reason.name : "UnhandledRejection";
var message = isError ? reason.message : String(reason);
var stack = isError && reason.stack
? reason.stack
: "(rejected with a non-Error value, so there is no stack)";
report(name + ": " + message.slice(0, 120), message + "\n\n" + stack);
});
// Lets game code file its own events through the same throttle.
window.reportGameError = report;
})();
The title is built to be identical for every player who hits the same bug: the error name plus file, line and column for thrown errors, and the name plus message for rejections. That matters because report trackers group on it. Bugnet stacks a report onto an existing one when the titles match exactly, so one bug becomes one entry with a count. The seen set sends each title once per page load, and the cap keeps a badly broken build from sending hundreds of different errors.
Things that go wrong without throwing
WebGL context loss. When the GPU process restarts, the tab sits in the background too long on mobile, or the page creates too many contexts, the browser takes the context away. Nothing throws. Draw calls silently do nothing and the canvas goes black. The canvas fires an event you have to listen for:
canvas.addEventListener("webglcontextlost", function (event) {
event.preventDefault(); // tells the browser you will handle a restore
window.reportGameError("WebGL context lost",
"Lost after " + Math.round(performance.now() / 1000) + " s of play", "other");
});
WebAssembly traps. Unity WebGL builds, Godot web exports and anything built with Emscripten run compiled code. When that code hits an invalid memory access or an abort, the browser throws a RuntimeError with a message such as memory access out of bounds or unreachable. It arrives through the normal error event, so the handler above reports it, but the stack is a list of numbered wasm functions unless the build kept function names. Engine loaders often show their own error banner as well, which is another reason to use addEventListener and leave window.onerror alone.
Workers. A Web Worker has its own global scope. Install the same listeners inside the worker script, or handle the error event on the Worker object in the page.
Noise, minified stacks and source maps
Not every error on your page is yours. Browser extensions inject scripts into every tab, and when they throw, your handler hears it. Their stack frames contain extension URLs, which is what the NOISE patterns above filter out. The “ResizeObserver loop” message is a browser warning about layout timing that reaches the error event and is safe to ignore.
A production stack trace from a minified bundle reads at t (game.min.js:1:48213). The whole file is one line, so the column number is the only coordinate that means anything. That is why the handler records colno. To turn it back into a file and line, build with source maps and keep the map for every version you publish. You do not have to upload the maps with the game. Keep them private and decode positions on your own machine, for example with the source-map package’s originalPositionFor. Always send the game version with the report so you know which map to open.
Sending the report: fetch keepalive, sendBeacon and iframes
navigator.sendBeacon is often recommended for telemetry because the browser will finish the request even if the page is closing. It has one limitation that rules it out here: you cannot set request headers, so an endpoint that authenticates with a header such as X-API-Key will reject it. fetch with keepalive: true gives the same survive-the-unload behaviour with full control over headers. Browsers cap the size of keepalive request bodies at roughly 64 KB, so truncate long descriptions as the handler does.
Games on portals usually run inside an iframe. On itch.io, for example, the game’s index.html is served from a separate itch domain and embedded in the store page. Error events fire on the window of the document where the error happened, so the listeners must be installed in your game’s own HTML, which is the iframe’s document. The outer page cannot see them. Two consequences: the request to your report endpoint is cross-origin, so the endpoint must allow CORS, and location.hostname is worth recording because it tells you which portal a report came from.
What the Bugnet Web SDK installs
The Bugnet Web SDK is one script that works with Phaser, PixiJS, Three.js or a plain canvas. With autoCaptureErrors on, which is the default, Bugnet.init() adds a window error listener and an unhandledrejection listener with addEventListener, so it coexists with anything else on the page. Each distinct error is filed once per session, up to 20 automatic reports, with the stack, the last 50 console lines, a screenshot of the game canvas, the user agent and the game version. Its endpoints accept requests from any origin, so it works from a portal iframe.
The SDK listens in the bubbling phase, so failed asset loads and context loss are not filed automatically. File those yourself from your loader or the webglcontextlost listener with Bugnet.reportBug(title, description, { category: "other" }). The same script provides the in-game report form for bugs players describe in their own words, and everything lands in one dashboard where matching titles stack with an occurrence count. The free plan covers one project and up to 100 bug reports in total. Setup is in the SDK docs.
Related guides
- Where Are HTML5 Web Game Crash Logs? Finding and Reading Them
- How to Fix a “WebGL context lost” Error in a Web Game
- How to Log Errors in an HTML5 Web Game
- Crash Reporting for Phaser Web Games
- Crash Reporting For Unity WebGL on itch.io
Frequently asked questions
What is the difference between window.onerror and unhandledrejection?
window.onerror, or the window error event, fires for exceptions thrown synchronously in event handlers, timers and requestAnimationFrame callbacks. unhandledrejection fires when a promise rejects and nothing catches it, which includes any exception thrown inside an async function. A game needs both.
Why does window.onerror only say Script error?
The script that threw was loaded from a different origin without CORS, so the browser hides the message, file and line. Set the crossorigin attribute to anonymous on the script tag and serve the file with an Access-Control-Allow-Origin header, and the full error is reported.
Does window.onerror catch failed image or script loads?
No. A failed load fires an error event on the element and that event does not bubble. A listener added to window with the capture flag set sees it for elements that are in the document. Images and audio created in code and never attached need their own onerror handler.
Why did my game freeze after a JavaScript error?
If the exception was thrown inside your requestAnimationFrame callback before the line that schedules the next frame, the loop never runs again. The page is still alive but nothing updates. Schedule the next frame first, or wrap the frame body in try and catch.
Can I use navigator.sendBeacon to send error reports?
Only if your endpoint needs no custom headers. sendBeacon cannot set a header such as X-API-Key. Use fetch with keepalive set to true, which also lets the request finish if the page is closing.
You need both listeners, registered with addEventListener before your game code loads, plus a throttle. One without the other misses half of what goes wrong.