Error logging - Robust Client-Side JavaScript

The standard approach is to monitor all exceptions on a page and to handle them centrally, for example using window.onerror. Then gather a bunch of context information and send an incident report to a log server. That server stores all reports, makes them accessible using an interface and probably sends an email to the developer.

Here is a simple global error reporter:

Javascript

window.onerror = function(message, file, line, column, error) {
	var errorToReport = {
		type: error ? error.type : '',
		message: message,
		file: file,
		line: line,
		column: column,
		stack: error ? error.stack : '',
		userAgent: navigator.userAgent,
		href: location.href
	};
	var url = '/error-reporting?error=' +
		JSON.stringify(errorToReport);
	var image = new Image();
	image.src = url;
};

This code sends a report to the address /error-reporting using a GET request.

The example above is not enough. It is not that easy to compile a meaningful, cross-browser report from an exception. Tools like TraceKit and StackTrace.js help to extract meaning from exceptions.

Quoted content by Mathias Schäfer is licensed under CC BY-SA. See the other snippets from Robust Client-Side JavaScript.

Tags: