Log client-side assertion errors to server

I’ve been writing a lot of python lately, and the assert statement is my new best friend. You use it like this:

assert a == b, "a did not equal b!"

I’ve also been writing a lot of javascript lately, and the console object has a similar assert method that can be used like so:

console.assert(a === b, 'a did not equal b');

Console asserts are pretty useless though unless you are debugging in a dev environment. Today I wanted to add some assert statements that would log assertion failures (with a stack trace) to the server. Here’s what I came up with.

var logger = function () {
    return {
        assert: function (test, msg) {
            msg = msg || "(no error message)";
            if (!test) {
                try {
                    throw Error();
                } catch (e) {
                    if (e.stack) {
                        this.logError(msg + '\n' + e.stack);
                    }
                }
            }
            // throw("Assertion failed with: " + msg);
        },

        logError: function (msg) {
            $.ajax({
                url: '/client-errors',
                type: 'POST',
                data: {msg: msg}
            }).success(function (response) {
                console.log('assertion error logged to server');
            }).error(function (response) {
                console.log('failed to log assertion to server');
            }).always(function (response) {
                console.log(msg);
            });
        }
    }
}();
 
3
Kudos
 
3
Kudos

Now read this

The first paying customer

Line by line your product begins to take shape. Bleary eyed and tired you push on, willing your brain to solve just one more piece of the puzzle before you call it a night. You’re excited. You’re creating something. The thought that... Continue →