How to handle error in Angular Controller from MongoDB database update/delete in Express?

时间:2016-08-31 17:29:42

标签: javascript angularjs node.js mongodb

I am trying to figure out how to handle an error when deleting or updating a document in MongoDB in Angular JS?

I have the following route in Node/Express:

  function handleError(res, reason, message, code) {

    console.log("ERROR: " + reason);
    //log the reason for the error
    res.status(code || 500).json({
      "error": message
    });

  }

app.delete("/polls/:id", auth, function(req, res) {

    db.collection(POLLS_COLLECTION).deleteOne({
      _id: new ObjectID(req.params.id), userID: req.user.id
       //userID must match the req.user.id from Passport to make sure the poll belongs to the user
    }, function(err, doc) {

      if (err) {

        handleError(res, err.message, "Failed to delete poll");

      } else {

        res.status(204).end();

      }


    });


  });

The following in an Angular JS controller:

$scope.deleteThisPoll = function(){

          Polls.deletePoll($routeParams.pollId)

           .then(function(response){

                    alert("Poll deleted!");

                    var url = "/mypolls/" + $scope.userID;

                    $location.path(url);

                }, function(response){

                    alert("Error deleting poll");

                    console.log(response);

                })

        };

deleteThisPoll in the controller calls a deletePoll service that sends a a request to the route:

   this.deletePoll = function(pollId){

        var url = "/polls/" + pollId;

        return $http.delete(url);


    };

What I want is to alert "Error deleting poll" from the Angular controller when the database delete is not executed (because for example user is not authenticated or the poll doesnt belong to the user) and "Poll Deleted" when the delete was successfull.

However: the error callback is never used and the app always alerts "Poll deleted!" no matter if the document was deleted or not deleted.

Doesn't my route send an error response when the delete was not executed and will it not hit my Angular error callback?

3 个答案:

答案 0 :(得分:0)

You can do like code below

Put this HTML code where you want to show error message :

<div style="color:red;">
{{error}}
</div>

In your angular js controller :

$scope.deleteThisPoll = function(){

      Polls.deletePoll($routeParams.pollId)

       .then(function(response){

                alert("Poll deleted!");

                var url = "/mypolls/" + $scope.userID;

                $location.path(url);

            }, function(response){

                $scope.error="Any error message you like to show";

                console.log(response);

            })

    };

答案 1 :(得分:0)

If your API return an error. you can catch it like this :

Polls.deletePoll($routeParams.pollId).then(function(response) {

   //SUCCESS CODE

}).catch(function(error) {
   //NOTIFY ERROR
   //NotifyService.display(error);
   console.log(error);
});

答案 2 :(得分:0)

谢谢你们。我发现MongoDB由于某种原因总是返回一个结果对象,即使没有删除/更新。我通过检查设置为1或0的result.deletedCount propety来解决这个问题。像这样:

  if(err){

    res.status(500).end();

  }

  if(result.deletedCount === 0){

    res.status(404).end();
    //error handling in Angular error callback

  } else {

    res.status(204).end();
    //error handling in Angular success callback
  }


});

});

这确保无论删除是否成功,都不会发送204。