The Gilt technology organization. We make work.

When Code Blows up and You Don't Know Why

Rather frequently, our code has an error, but we don’t know about it because no error is logged in the console. We quite often don’t find out until we fall flat on our faces while trying to use the site.

There are several potential culprits (require, when, and underscore come to mind as serial offenders), but I’d like to take a moment to talk about when.js in particular, and “one simple trick” that will make all your errors visible.

when.js is understandably paranoid about one promise callback blowing up and preventing others from firing, and so they wrap every call to any callback in a try catch. A quick scan of when.js will find five try catch blocks: One each for resolved/rejected/progressing, and two for a couple of internal functions. Fortunately, the authors of when.js were also aware that this could swallow error messages, so they put in place a very simple (and deceptively subtle, unfortunately) mechanism for surfacing these errors. Simply put, it returns a new rejected promise.

Easy, eh? The deceptive part is that you can’t use the second param (onReject) callback of .then(fn, fn); you have to explicitly call .otherwise(fn);. I suspect this is either because of some internal queue that gets short circuited, or more likely, that it’s a separate promise entirely, which implies that you can have greater control over “normal” errors vs. “bad” errors.

Here’s a code sample:

myPromise.then(function (data) {
  // this is the resolved callback
}, function (error) {
  // this is the rejected callback, btw, NOT the on error callback
}).otherwise(function (error) {
  // THIS is the error callback
  // better alternative, if you have an instance of Logger:

All you have to do to get error reporting is to append that .otherwise(…) to the end of your promise chain!

Kevan Davis 5 Gilt 340 Gilt Groupe 282 gilttech 332 front-end engineering 11 software engineering 66 programming 1 when.js 1