Search code examples
angularjsangular-http

Angular $http best practices


I am writing an angular service which I will use to get and manipulate data from SharePoint lists/libraries. I am trying to use best practices for $http promises but I am having trouble finding the best way to accomplish what I want. Here is one of my functions in my service:

this.GetListItemById = function (webUrl, listName, itemId, loading) {
    var url = webUrl + "/_vti_bin/listdata.svc/" + listName + "(" + itemId + ")";

    return $http({
        url: url,
        method: 'GET',
        processData: false,
        headers: { "Accept": "application/json;odata=verbose" },
    }).then(function SuccessCB(response) {
        return response.data.d;
    }).catch( function FailureCB(response) {
        throw response;
    });
};

And then here is where I use it in my controller:

$scope.GetListItemById = function (webUrl, listName, itemId) {
    SPListUtility.GetListItemById(webUrl, listName, itemId)
        .then(function success(data) {
            console.log(JSON.stringify(data));
            $scope.animateAlert("myAlert", "alertText", "Item: " + data.Title + " loaded", "success");
        }).catch( function failure(error) {
            console.log("Error " + error.status + ": " + error.statusText);
            $scope.animateAlert("myAlert", "alertText", "Error " + error.status + ": " + error.statusText, "danger");
        });
};

This is working as intended, it returns the item data if it is found on the server and if it is not then the 404 bubbles up to my controller and my error alert is called and logged to the console. My problem with this though is it keeps bubble up and angular catch statements are tripped which causes the following in the log: Console log image

Is there a way to stop angular from blowing out the log? Also am I following best practices here? If not what should I change?


Solution

  • When you throw inside a catch block it doesn't just reject the promise. It also triggers angular's exception handler which by default will log the exception (you can replace the default implementation of this if you want). If you wanted to reject a promise from a reject block without triggering the exception handler you could return a rejected promise. e.g.

    return $q.reject(response);

    That being said your catch block that is throwing the response isn't necessary. The exact same behavior will occur if you just remove it (except for the logging)