Question

I'm writing an app using knockout and I'd like to be able to catch any errors in my code which are run inside of knockout, for example a subscription.

Currently I have a knockout subscription:

var myObservable = ko.observable();
myObservable.subscribe(function (val) {
    // Code here is error prone
});

I'd like to be able to use the above pattern throughout my app but be able to catch any errors thrown in the subscription callback.

My current solution is to wrap the ko.subbscribable.fn.subscribe function with an error handler, like so:

var _subscribe = ko.subscribable.fn.subscribe;
ko.subscribable.fn.subscribe = function (callback) {
    if (arguments.length != 1) return _subscribe.apply(this, arguments);
    else return _subscribe.apply(this, [function () {
        try
        {
            callback.apply(this, arguments);
        }
        catch (err) {
            // handleError is a function in my code which will handle the error for me
            handleError(err);
        }
    }]);
};

My question is are there any hidden side affects with this approach, or is there a better approach I'm missing.

Was it helpful?

Solution

This is good approach, basically called duck punching, see great explanation from Paul Irish

http://www.paulirish.com/2010/duck-punching-with-jquery/

I would only update the code to handle error also in case more arguments are passed into subscribe function, like this

var _subscribe = ko.subscribable.fn.subscribe;
ko.subscribable.fn.subscribe = function () {
    try {
        return _subscribe.apply(this, arguments);
    }
    catch (err) {
        // handleError is a function in my code which will handle the error for me
        handleError(err);
    }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top