How to handle knockout subscription errors

I am writing an application with a knockout, and I would like to catch any errors in my code that run inside a knockout, for example, a subscription.

I currently have a knockout subscription:

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

I would like to be able to use the above template throughout my application, but be able to catch any errors that occurred in the subscription callback.

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

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 whether there is any hidden side that affects this approach, or is there a better approach that I am missing.

+3
source share
1 answer

, , . Paul Irish

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

, , ,

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);
    }
};
0

All Articles