Sunday, May 5, 2013

Maintain error output in Promises/A+

The Promises/A+ spec requires that you catch exceptions in a callback and use that signal to reject the enclosing promise. Unfortunately, Javascript exceptions catch semantic mistakes (typos) along with application-level faults.

promise(someAsync()).then(function(result) {
    return resul.doSomething(); // typo, never gets logged
}).then(function(result2) {
    // never gets called!
});

How do you catch programming errors when using promises? If you're in Chrome, you can set the debugger to stop on all exceptions, but that's not ideal. If you maintain the promise lib, try this:

var newValue;
try { newValue = fn(parentPromise.value); }
catch (e) {
    if (e instanceOf Error) {
        if (console.error)
            console.error(e, e.stack);
        else console.log("Promise exception thrown", e, e.stack);
    }
    targetPromise.reject(e);
}

And tada, you now have a stack dump logged with your errors. Most application-level rejections are not Error types (eg throw "not found") so the noise stays pretty near to expectations.

No comments:

Post a Comment