|
"Theoretically, we could wrap every function call in a try/catch and we'd
have an error object in the catch block. This is bad; please don't try.
You'll have a particularly hard time with asynchronous callbacks anyways."
Couldn't disagree more with this point. Wrap the function, not the call. Something like this: function logExceptions( fn ) {
return function() {
try {
return fn.apply( this, arguments );
} catch( e ) {
logException( e );
}
};
}
myFunction = logExceptions( function() {
// do stuff
} );
Now you just call myFunction() normally. Pretty painless.Further, you only have to use a logger-wrapped function for your script's entry points, not "every function": the initialization method (if any), event handlers, setTimeout callbacks, etc. Since you're probably already calling non-native methods which wrap those APIs, that method can handle exception log wrapping for you, too. For example, for event handling I call an internal on(obj, "name", function(){}) method, and on() passes the callback through logExceptions() for me. |