Javascript Global Error Handler

Today i’have created a simple class to log in the backend the javascript error, so i can have a real time monitoring of how error appear to the users.

We can use a window.onerror and the addEventListener rewrite.

Window.onerror has been available in most browser, but the argument that are passed on each browser are different:

IE 11
IE 10
IE 9, 8
Safari 10 and up
Safari 9
Android Browser 4.4

This is my class with a _wrap function, and a SendError that trasmit the data on the backend

class ErrorHandler {

	constructor() {
		let $this = this;

		window.onerror = function (message, file, line, col, error) {
			let data = message+" from "+error.stack;

	_prototypeInit() {
		let $this = this;
		var addEventListener = window.EventTarget.prototype.addEventListener;
		window.EventTarget.prototype.addEventListener = function (event, callback, bubble) {, event, $this._wrap(callback), bubble);
		var removeEventListener = window.EventTarget.prototype.removeEventListener;
		window.EventTarget.prototype.removeEventListener = function (event, callback, bubble) {, event, callback._wrapped || callback, bubble);

	_wrap(func) {
		let $this = this;
		if (!func._wrapped) {
			func._wrapped = function () {
				try {
					func.apply(this, arguments);
				} catch (e) {
					let data = e.message+" from "+e.stack;
					throw e;
		return func._wrapped;

	SendError(message) {
		let $this = this;
		fetch('/ErrorHandler/WriteLog', {
			method: 'POST',
			body: JSON.stringify({ message: message }),
			headers: {
				'Content-Type': 'application/json'
		}).then(res => res.json()).catch(error => console.error('Error:', error));

In the message we put the stacktrace.
To use it at the init of your application:
let handlerError = new HandlerError();

Write to me if you have some suggestion to improve it.


"Javascript is to Java as hamburger is to ham; both are delicious, but they don't have much in common except a name" I'm javascript lovers and this is my site on witch sometimes write about my experience, when i have some free time, and remember: "Homo faber fortunae suae"

Leave a Reply

2 Comment authors
Webdesignvalley.comminnesota web design Recent comment authors
newest oldest most voted
Notify of
minnesota web design

Informative post,It is useful for me to clear my doubts.I hope others also like the information you gave in your blog.

These are really amazing and valuable websites you have share with us. Thanks for the informative post. Keep posting like these information.