Asynchronousity

Back

If you’ve ever dealt with asynchronous functions (and I’ll wager you have). You’ll know what a nightmare it can become to debug them in a large application. Recalling a stored function and running it in a try catch block leaves you left with unhelpful error messages that just lead you back to where you called them, rather than the root of the problem, the erroneous code.

TypeError: Failed to set the ‘body’ property on ‘Document’: The provided value is not of type ‘HTMLElement’.

at TypeError (native)

at http://fiddle.jshell.net/raininglemons/ddhhq78u/show/:43:19

at http://fiddle.jshell.net/raininglemons/ddhhq78u/show/:33:13

(anonymous function) @ (index):35

Unless you’re involved enough to delve into breakpoints. This error message just points us towards are rather useless call of the broken function.

var async = function (fn) {
    setTimeout(function () {
        try {
            fn();
        } catch (e) {
            console.error(e);
        }
    }, 0);
};

How do we fix this?

Well, it turns out its actually quite simple. All we need to do is log the stack of the error object we’ve received and chrome will properly log all the line numbers and file references. Chances are you’re also probably working with a js framework so don’t want to start fishing through there for any instance that an error is logged. So replacing the console.error object, we can cover all our bases.

(function () {
    "use strict";

    var native = console.error, i;

    console.error = function error () {
        for (i = 0; i < arguments.length; i++)
            if (arguments[i] instanceof Error)
                arguments[i] = arguments[i].stack;
        native.apply(this, arguments);
    };
})();

Here, all we’re doing is replacing any Error objects with their stack value then passing all arguments then back onto Chrome’s error handler.

Then the result?

TypeError: Failed to set the ‘body’ property on ‘Document’: The provided value is not of type ‘HTMLElement’.

at TypeError (native)

at http://fiddle.jshell.net/raininglemons/ddhhq78u/show/:63:19

at http://fiddle.jshell.net/raininglemons/ddhhq78u/show/:33:13

error @ (index):55

Which points us to;

async(function () {
    console.warn("I'm the broken bit of code!");
    document.body = 5;
});

Mental health maintained another day.