javascript - Return error through promise -


i pretty new angularjs , javascript. creating app in planning use 1 function ajax related operation(factory in angularjs). function 1 gateway ajax operations. when return promise success works properly. returning error promise not work.

here sample code. expecting return of promise in error function if promise fails goes success

var myapp = angular.module('myapp', []);  myapp.controller('firstcontroller, function($scope, util){         util.doajax().then(function(response){                 // function called in both success , error             }, function(err){                 // never called why ?                             }); });  myapp.factory('util, function($http){     return $http({        method: 'get',        url: 'http://www.example.com'     }).then(function(response){         // return success promise         return response;     }, function(err){         // should return error promise         return err;     }); }); 

currently directly returning data error function, chaining promise , calling underlying .then method.

while returning error have reject promise creating new custom promise using $q

return $q.reject(err) 

other important thing is, should create method in service name

myapp.factory('util', function($http, $q){  //exposed method  return {    doajax : function() {        return $http({           method: 'get',           url: 'http://www.example.com'        }).then(function(response){            // return success promise            return response.data; // returned data        }, function(err){            // return error promise err object            return $q.reject(err);        });      }   } }); 

Comments