knockout js best practices ajax error handling

knockout js best practices ajax error handling

Asked on December 25, 2018 in knockout js.
Add Comment


  • 2 Answer(s)

        Use the base class method for error handling :

        See the ex code :

    errorHandlingViewModel = function () {
        var self = this;
        self.ErrorText = ko.observable();
        self.errorHandler = function (jqXHR, textStatus, errorThrown) {
            self.ErrorText('An error has occured, please refresh the page and try again in a little while. (' + textStatus   + ':' + errorThrown + ')');
        };
        self.validationErrorHandler = function (err) {
            //todo
            alert('validation error ' + err);
        }
        self.successHandler = function (data, onSuccess) {
            if (data.result == "success") {
                if (onSuccess) {
                    onSuccess(data.data);
                }
            }
            else {
                if (data.data && data.data.Tag) {
                    if (data.data.Tag == "ValidationError") {
                        validationErrorHandler(data.data.Tag);
                    }
                }
                errorHandler(null, data.result, data.data);
            }
        };
    };
    

        The observable ErrorText field is there .

        Every ViewModels should  use prototypal inheritance, If the error handling is needed,

    viewModel.prototype = new errorHandlingViewModel();
    var mainViewModel = new viewModel();
    ko.applyBindings(mainViewModel, $("#locationTOApplyBindingTo")[0]);
    

        In this view models, The  ajax calls look like:

    $.ajax({
        type: 'POST',
        url: myURL,
        data: myData,
        success: function (data) {self.successHandler(data,success);},
        error: self.errorHandler
    }); //end ajax
    

        The most easy  data-bind is data interface :

    <div class="error" data-bind="visible:ErrorText">
        <div class="innerMSGContainer">
          <div class="innerMSG" data-bind="text:ErrorText"></div>
        </div>
    </div>
    
    Answered on December 25, 2018.
    Add Comment

    Updating the knockout model  will leave the model on the safest state .

      If there is any error due to some reason which should be informed  to the user,  Use this  humane.js   . In 3 cases for model error, no response or server error, Then the state of error function which  should be send to user .

        Then check this things again and do their own thing :

    $.post("somewhere")
    .success(function() {
        // update knockout models here
    })
    .error(function() {
        // show error message to user
    })
    .complete(function() {
        // reset any temporary variables
    });
    

    Answered on December 25, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.