I'm using the code below in order to simplify the backend requests but I didn't catch how to call either a success method or an error method.
How can I reach the expected behavior commented in the code?
 
app.factory('REST', function ($http, $q, sweetAlert) {
    return {
        load: function (module, action, data) {
            var deferred = $q.defer();
            var promise = deferred.promise;         
            $http
            .post('/api/'+module+'.php?action='+action, data)
            .success(function (data) {
                if(data.error)
                {
                    sweetAlert.swal({
                        title: "Error",
                        text: data.error,
                        type: "warning"
                    });
                //HERE I WANT TO CALL .error(details)
                }
                else
                    deferred.resolve(data.result);
                        }).error(function () {
                //HERE I WANT TO CALL .error(details)
            });
            promise.success = function(fn) {
                promise.then(fn);
                return promise;
            }
            return promise;
        }
    };
});
This is the code which uses the code above:
$scope.login = function () {
    $scope.loading = true;
    var payload = {'credentials': $scope.logindata};
    REST.load('access', 'login', payload).success(function(data) {
        if(data.redirect)
            $state.go(data.redirect);
        $scope.loading = false;
    }).error(function(data) { //THIS SHOULD BE CALLED
        $scope.loading = false;
    });
}
 
     
    