0

The error I get in the console log using error.status is -1 yet the data I sent to the database was successfully posted. The data shows in my ng-repeat I have for the list. It's very odd because it happens 5% of the time.

Here is my Controller:

    angular.module('app')
.controller('WebsiteCtrl', ['WebsiteService', '$scope', '$http', '$timeout', '$uibModal', function (WebsiteService, $scope, $http, $timeout, $uibModal, $uibModalInstance) {
    $scope.model = WebsiteService.getWebsites();
    $scope.clients = WebsiteService.getClients();
    $scope.new = {
        Website: {}
    };

    //create alerts when page reloads after crud functions
    if (localStorage.getItem("Success")) {
        $scope.alert = "Success";
        $scope.alertMessage = localStorage.getItem("Success");
        localStorage.clear();
    } else if (localStorage.getItem("Error") && localStorage.getItem("Error") != null) {
        //sometimes get errors even when adding, deleting, updating is successful
        $scope.alert = "Error";
        $scope.alertMessage = localStorage.getItem("Error");
        localStorage.clear();
    };


    //Obtains list of websites from WebsiteSvc
    getWebsites(); // this initializes Website List on page load
    function getWebsites() {
        WebsiteService.getWebsites()
            .then(
            function (data) {
                $scope.model = data;
            },
            function (errResponse) {
                console.log("Error while getting websites");
            });
    }

    getClients();
    function getClients() {
        WebsiteService.getClients()
        .then(
        function (data) {
            $scope.clients = data;
        },
        function (errResponse) {
            console.log("Error while getting Clients");
        });
    }

    //add a website
    $scope.addWebsite = function () {
        var data = WebsiteService.addWebsite($scope.new.Website).then(
            function (success) {
                localStorage.setItem("Success", "Added Website Id:" + success.Id + " Successfully!");
            },
            function (error) {
                console.log(JSON.stringify(error, null, 2));
                console.log(error.statusText);
                localStorage.setItem("Error", "Error while adding website! " + error.status + ":" +  error.statusText);
            }
        );
        //location.reload();
    }

    //update a job
    $scope.updateWebsite = function (website) {
        WebsiteService.updateWebsite(website).then(
            function (success) {
                localStorage.setItem("Success", "Updated Website Id:" + success.Id + " Successfully!");
            },
            function (error) {
                localStorage.setItem("Error", "Error while updating website! " + error.status + ":" + error.statusText);
                console.log(error);
            }
        );
        location.reload();
    }
    // deletes website
    $scope.deleteWebsite = function (website) {
        var indx = $scope.model.websiteList.indexOf(website);
        WebsiteService.deleteWebsite(website.Id).then(
            function (success) {
                localStorage.setItem("Success", "Deleted Website Id:" + success.Id + " Successfully!");
            },
            function (error) {
                localStorage.setItem("Error", "Error occured while deleting website! " + error.status + ":" +  error.statusText);
            }
        );
        location.reload();
    }

    //toggles active 
    $scope.updateActive = function (w) {
        if (w.Active === true) {
            w.Active = false;
        } else if (w.Active === false) {
            w.Active = true;
        }
        //updates job to reflect gui (active or inactive)
        this.updateWebsite(w);
    }

    //select job
    $scope.selectWebsite = function (w) {
        $scope.selectedWebsite = w;
    }

    //show modal function
    $scope.showModal = function (action, obj) {
        $scope.showBool = true; //boolean to be able to exit modal after update
        $scope.model.runButtonText = "Run Job"; //this is for run job only
        $scope.$modalInstance = $uibModal.open({
            scope: $scope,
            inputs: {
                title: action + " Job"
            },
            restrict: "E",
            templateUrl: 'app/modal/WebsiteModals/modal' + action + 'Template.html',
            controller: "JobCtrl",
            backdrop: 'static',
            keyboard: false

        });
    }

    //exit modal function
    $scope.exitModal = function () {
        $scope.$modalInstance.dismiss('cancel');
    };


}]);

My Service:

    //Website Service class that executes the CRUD functionality
angular.module('app').factory('WebsiteService', ['$http', '$q', function ($http, $q) {

    var factory = {
        getWebsites: getWebsites,
        getClients: getClients,
        addWebsite: addWebsite,
        updateWebsite: updateWebsite,
        deleteWebsite: deleteWebsite,
    };

    return factory;

    //creates service call for getWebsites
    function getWebsites() {
        var deferred = $q.defer();
        $http.get('Websites/GetWebsites')
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function (errResponse) {
                console.log('Error while getting websites');
                deferred.reject(errResponse);
            }
        );
        //returns a promise that function was successful or failed
        //helps control asynch calls
        return deferred.promise;
    };

    //creates service call for getClients
    function getClients() {
        var deferred = $q.defer();
        $http.get('Websites/GetClients')
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function (errResponse) {
                console.log('Error while getting websites');
                deferred.reject(errResponse);
            }
        );
        //returns a promise that function was successful or failed
        //helps control asynch calls
        return deferred.promise;
    };

    function addWebsite(website) {
        var deferred = $q.defer();
        console.log('Service: ', website);
        $http.post('Websites/Post', website)
            .then(
            function (response) {
                deferred.resolve(response.data);
                console.log(response.data);
            },
            function (errResponse) {
                console.log("Error while adding website");
                deferred.reject(errResponse);
            }
        );
        //returns a promise that function was successful or failed
        //helps control async calls
        return deferred.promise;
    };

    function updateWebsite(website) {
        var deferred = $q.defer();
        $http.post("Websites/Post", website)
            .then(
            function (response) {
                deferred.resolve(response.data);
                console.log(response.data);
            },
            function (errResponse) {
                console.log("Error while updating website");
                deferred.reject(errResponse);
            }
        );
        //returns a promise that function was successful or failed
        //helps control async calls
        return deferred.promise;
    };

    function deleteWebsite(id) {
        var deferred = $q.defer();
        console.log('Service: ', id);
        $http.post("Websites/Delete/" + id)
            .then(
            function (response) {
                deferred.resolve(response.data);
                console.log(response.data);
            },
            function (errResponse) {
                console.log("Error while deleting website");
                deferred.reject(errResponse);
            }
        );
        //returns a promise that function was successful or failed
        //helps control async calls
        return deferred.promise;
    };

}]);

It happens on all database related functions, but I was using my addWebsite function to get useful data back. It's hard to debug when it happen so rarely.

Any help would be greatly appreciated! Thanks in advance!

EDIT Here is a picture of getting error as -1 and showing the network tab. This is in a different tab but it's the same code. enter image description here

DDelgro
  • 463
  • 1
  • 6
  • 16
  • Seems to me that the problem must be in your api. You probably don't get a 201 back from the api – devqon Jan 12 '17 at 15:29
  • It's possible since I am throwing json blobs of data at Microsoft's Entity Framework. But Is there anyway to know for sure? I am at a total loss because I show success and error messages to user and it's not really professional showing a one time error! :( – DDelgro Jan 12 '17 at 15:33
  • Debug your API or (if applicable) read the logs of your API. You can be sure by watching the 'Network' tab in your browser console and see if you get any errors back – devqon Jan 12 '17 at 15:34
  • You should be able to see in chrome developer console the status code of your request. – Michal Takáč Jan 12 '17 at 15:38
  • Updated post to show picture of error happening. Also show the network console. – DDelgro Jan 12 '17 at 15:39
  • Also, is it possible the post or get requests are firing too fast where the browser actually cancels the request? – DDelgro Jan 12 '17 at 15:43

1 Answers1

1

According to angularjs documentation: "A response status code between 200 and 299 is considered a success status and will result in the success callback being called. Any response status code outside of that range is considered an error status and will result in the error callback being called. Also, status codes less than -1 are normalized to zero. -1 usually means the request was aborted, e.g. using a config.timeout. Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning that the outcome (success or error) will be determined by the final response status code." See it: https://docs.angularjs.org/api/ng/service/$http.

  • So can I ignore the error if it is -1 then? Such as add an if statement within the error function checking if it's -1. – DDelgro Jan 12 '17 at 16:02
  • It is better not to ignore. Check if it starts duplicate requests (first one finishes successfully and second one is refused or timeout). Try other timeout values to your requests.Check out about timeout of your webservice too. – Holanda Junior Jan 12 '17 at 16:14
  • As far as I can tell I have no duplicate requests. The only thing I can think of to cause this is the speed of the request. If it fires off too fast. – DDelgro Jan 12 '17 at 16:20
  • In fact, looking at the photo about the request, it seems it has been cancelled before the timeout could be reached, is it not? Check it out about request's 'stalled' status and compare it to timeout. Anyway, try to increase your timeout since the webservice operation involves costly operation such as accessing database. – Holanda Junior Jan 12 '17 at 16:33
  • Thank you, I will look into this. This solves my problem for the most part being that I now know the status codes for angular. Thanks again! – DDelgro Jan 12 '17 at 16:34
  • Great! Cheers! :) – Holanda Junior Jan 12 '17 at 16:42