1

How do I handle server side errors with angularjs. I saw a few solutions, like How to properly handle server side errors?, but they don't really fit my needs/maybe I need to change my failing behavior. Note that I am handling the routing on server side.

My problem is that on server side I run a few mongo queries which I return to my routes. Note that these queries may generate custom errors as well (like a field's length is not appropriate). E.g.:

Server Side

ingredientController

controller.getIngredient = function(cb) {
    Ingredient.findOne({},cb)
}

in my route handler I call this function:

function(req, res) {
ingredientController.getIngredient(function(err, data) {
    if (err)
        res.json({
            error: 1
        })
    else
        res.json({
            error: 0,
            data: 'success'
        })
})
}

Note that in the json could contain the error message as well.

Client Side

productServices.getIngredient()
        .success(function(result) {
             //error should be handled here e.g. result.error === 1
             $scope.ingredient = result.data
        })
        .error(function(err) {
             console.log('error ' + err)
        })

Am I doing it right? If yes, then how should I give some feedback to the user.

Community
  • 1
  • 1
Pio
  • 4,044
  • 11
  • 46
  • 81

1 Answers1

1

One solution is to create a service and directive that displays the error message. Load up the directive in your main template and then use the service to update it.

Another option is to use the angular-growl library:

angular.module('MyModule').service(
  'MyService',
  function (growl) {
    this.getDatabaseResult = function () {
      getResult().then(
        function (result) {
          growl.addSuccessMessage('Success!');
        },
        function (error) {
          growl.addErrorMessage('Get Database Result Error: ' + error);
        }
      );
    }
  }
);
  • So I need to call this service's `getDatabaseResult` in each `ajax` request's `success` with the `error` parameter? Also could you update your result that it is not general -- you can keep the general form -- but it applies to my exact question? – Pio Aug 01 '14 at 17:47
  • @Pio you would call growl's addSuccessMessage or addErrorMessage –  Aug 01 '14 at 18:22