cyberwombat
cyberwombat

Reputation: 40084

Return error message on $http call

In Angular I make an $http request and would like to return an error message just not sure how.

In Express I would like to do the following (or similar) upon errors.

res.send(400, { errors: 'blah' });  

In Angular I currently have this:

$http.post('/' ,{}).then(function(res) { }, function(err) {
  console.log(err) // no errors data - only 400 error code
});

How can I access "errors" (i.e. "blah") from within Angular?

Upvotes: 1

Views: 1000

Answers (2)

disgra
disgra

Reputation: 783

I know it's an old question but.. I believe what you wanted was:

angular.module('App').factory('MainFactory', function($http) {
  return {
    post: function(something) {
      $http
        .post('/api', something)
        .then(function(result) {
          return result.data;
        }, function(err) {
          throw err.data.message;
        });
    }
  };
});

and from one controller

angular.module('App').controller('Ctrl', function($scope, MainFactory ) {
    $scope.something_to_send = "something"
    MainFactory
      .post($scope.something_to_send)
      .then(function(result){
        // Do something with result data
       }, function(err) {
        // showError(err);
    });
});

Upvotes: 0

Fals
Fals

Reputation: 6839

$http message provides, success and error function:

$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

If something goes wrong, like a server error, or another http erro the error function will be trigger and you can catch the error.

If something else trigger or you must provide some kind of feedback to the user, you can use the success method, but returning the data as domething else like this:

data {message: 'your message here', success: /*true or false*/, result: /*some data*/ }

Then in the success function:

$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
  if(data.success) {
     // do stuff here
  }
  else {
    // show the error or notification somewhere
  }
}).
error(function(data, status, headers, config) {
  //do stuff if error 400, 500
});

Upvotes: 1

Related Questions