Extending Javascript Errors
With my most recent project, I wanted to start using "proper" OO-style error handling instead of simply dealing with generic browser errors (that are generally super unhelpful). My tech stack is essentially as follows (not that it really matters):
Pyramid backend
require.js for async loading of my packages
jquery and jquery-ui for DOM manip
In my project, I'm utilizing browser-specific indexedDB implementations (as there doesn't yet to be anything consistent cross-browser - not surprised). I wanted to simply start off with a webkit-specific implementation and then eventually (if needed), add moz and others. I wanted to be really obvious when there was a database-related error as I'm expecting that I'll have some users try to access the page from an unsupported browser (this is a small application with a low user base, so I really don't mind limiting browser support). So, I decided to implement a custom error class, which ended up being super easy to implement, and super useful from within Chrome's console:
I have a core.js file that looks something like this (using require.js module defs):
define('lib/core', function() { // force into global scope by not using 'var' DatabaseError = function(msg) { this.message = msg || "(No message)"; this.stack = (new Error()).stack; }; DatabaseError.prototype = new Error; DatabaseError.prototype.name = 'DatabaseError'; });
From my view-specific js, I have something like this:
require(['lib/core'], function() { (function(){ this.initialize = function() { var req = webkitIndexedDB.open('mydbname'); req.onsuccess = this.onOpened; req.onerror = this.onError; }; this.onOpened = function(e) { // do happy stuff }; this.onError = function(e) { throw new DatabaseError('Something bad happened here'); }; })().initialize(); });
Now from my application (as long as the dependency is loaded), I can use DatabaseError with custom messages and be able to print out the callstack if required.
Helpful.













