0

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
  • I think your route doesn't send an http error. Use fiddler to visualize your response API. If your API return an HTTP error, catch the error from my example. Commented Aug 31, 2016 at 17:52
  • maybe if there is no document found with right _id and userID, there is no delete/update, but it is not considered an error? and i need to send a response when that is the case? Commented Aug 31, 2016 at 17:59
  • there are a lot of http code (restapitutorial.com/httpstatuscodes.html). In your case, you have to use a 404 error. And you have to do a specific action in your angular code. Commented Aug 31, 2016 at 18:04

3 Answers 3

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);

            })

    };
Sign up to request clarification or add additional context in comments.

Comments

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 Comments

isnt that the same as the error callback in my then function or is there a difference with the catch method?
No it's not really the same. suppose that your success code throw an error, you can catch error from catch method.
0

thanks guys. I found out that MongoDB for some reason always returns a result object even when there was no delete/update. I solved this by checking for the result.deletedCount propety that is set to 1 or 0. Like so:

  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
  }


});

});

this makes sure that not always a 204 is send whether or not the delete was successfull.

1 Comment

Did you know you can accept your own answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.