views:

342

answers:

2

I have a custom exception class which I'm using for a particular situation. It could be thrown from anywhere so try/catch isn't really practical.

throw new CustomException;

I want to catch this error in window.onerror and filter it out, which works fine in most browsers I've tested so far.

var window_onerror = window.onerror || function() {return false;};
window.onerror = function(message, url, line)  {
  if (message.match(CustomException.prototype.name)) {
    return true;
  } else {
    return window_onerror(message, url, line);
  }
};

However, in IE the window.onerror function receives Exception thrown and not caught instead of my custom exception.

A: 

I don't know of any way to retrieve the thrown object within the onerror handler. As a workaround, I suggest throwing a generic runtime error with a custom message, ie

throw new Error('foo')

and check

message === 'foo'

inside the handler function.

edit: working example code:

window.onerror = function(message, url, line)  {
    alert(message === 'foo');
    return true;
};

throw new Error('foo');
Christoph
I'll grant you that it works in IE, (which is what I asked) but Firefox reports only `Script Error` with that technique.
Justin Love
@Justin: works fine for me - can we see some code?
Christoph
http://bitbucket.org/JustinLove/module/src/4f80d66afb94/ See script/cgd/Module.js tested in qunit/index.html Throw is on line 126, with exception definition and handler starting on 196.
Justin Love
+1  A: 

We have a universal Exception handler which we use on Exceptioneer.com however each browser behaves differently and reports the same exceptions in different ways.

Also, different localised versions of browser act in different ways, for example, I've seen Javascript errors in Russian from some of our users - not the easiest thing in the world to parse.

This script will let you see how different browsers act to errors: -

window.onerror = function(message, uri, line) {
    var fullMessage = location.href + '\n' + uri + '\n' + line;
    alert(fullMessage);
    return false;
}

Thanks,

Phil.

Plip