Reputation: 4064
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.
Upvotes: 1
Views: 205
Reputation:
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);
}
);
}
}
);
Upvotes: 1