deferred - AngularJS Handle different error codes in different places -
i have service contains generic call $http ajax calls uses. here have "centralized" error handling status codes results in redirects.
"fieldssync" service:
return $http({ method: 'post', url: url, data: $.extend(defaultpostdata, postdata) }).error(function(data, status) { switch (status) { case 401: // "unauthorized". not logged in. redirect.tologinpage(); break; case 403: // "forbidden". role has changed. redirect.tologoutpage(); break; } });
when calling 1 of service functions controller return deferred object able hook more error callbacks able handle errors should result in kind of feedback user.
controller:
fieldssync.createfield(newfield).success(function(data) { ... }).error(function(data, status) { switch (status) { // <--- not want case 401: case 403: return; // these errors handled (=redirects) in generic error callback , don't want show while redirects. } ... // "individual" error handling. =displaying messages , stuff });
but because don't want error messages popping before redirect occurs have exit error callback if status codes have been handled.
the question is: how rid of switch cases in controllers? possible exit chain of error callbacks when specific error code has been handled? or possible work around in less ugly way? :)
this reoccurring problem me, , mind seems stuck.
i have checked docs , cant find pretty solution in either $http or $q.
i propose use responseinterceptor handle cases:
http://docs.angularjs.org/api/ng.$http
i wrote following, when had same "problem" you. first draft, can improve needs
internalservererrorresponseinterceptor = function($q, internalservererrorservice) { return function(promise) { return promise.then(function(response) { return response; }, function(response) { if (response.status > 499) { internalservererrorservice.handleerror(); return $q.reject(response); } return $q.reject(response); }); }; }; module.factory('internalservererrorresponseinterceptor', ['$q', 'internalservererrorservice', internalservererrorresponseinterceptor]); module.config(['$httpprovider', function($httpprovider) { $httpprovider.responseinterceptors.push('internalservererrorresponseinterceptor'); }]);
now specific internalservererrorservice can handle way want handled :)
regards
Comments
Post a Comment