added exception handling to $xhr

This commit is contained in:
Misko Hevery 2010-05-19 12:00:44 -07:00
parent f2abbfd394
commit 31b35b141f
2 changed files with 23 additions and 10 deletions

View file

@ -196,7 +196,7 @@ angularService('$route', function(location, params){
return $route;
}, {inject: ['$location']});
angularService('$xhr', function($browser, $error){
angularService('$xhr', function($browser, $error, $log){
var self = this;
return function(method, url, post, callback){
if (isFunction(post)) {
@ -218,12 +218,14 @@ angularService('$xhr', function($browser, $error){
{method: method, url:url, data:post, callback:callback},
{status: code, body:response});
}
} catch (e) {
$log.error(e);
} finally {
self.$eval();
}
});
};
}, {inject:['$browser', '$xhr.error']});
}, {inject:['$browser', '$xhr.error', '$log']});
angularService('$xhr.error', function($log){
return function(request, response){

View file

@ -1,10 +1,12 @@
describe("service", function(){
var scope, xhrErrorHandler;
var scope, $xhrError, $log;
beforeEach(function(){
xhrErrorHandler = jasmine.createSpy('$xhr.error');
$xhrError = jasmine.createSpy('$xhr.error');
$log = {};
scope = createScope(null, angularService, {
'$xhr.error': xhrErrorHandler
'$xhr.error': $xhrError,
'$log': $log
});
});
@ -201,13 +203,22 @@ describe("service", function(){
xhr.expectPOST('/req', 'MyData').respond(500, 'MyError');
scope.$xhr('POST', '/req', 'MyData', callback);
xhr.flush();
var cb = xhrErrorHandler.mostRecentCall.args[0].callback;
var cb = $xhrError.mostRecentCall.args[0].callback;
expect(typeof cb).toEqual('function');
expect(xhrErrorHandler).wasCalledWith(
expect($xhrError).wasCalledWith(
{url:'/req', method:'POST', data:'MyData', callback:cb},
{status:500, body:'MyError'});
});
it('should handle exceptions in callback', function(){
$log.error = jasmine.createSpy('$log.error');
xhr.expectGET('/reqGET').respond('first');
scope.$xhr('GET', '/reqGET', null, function(){ throw "MyException"; });
xhr.flush();
expect($log.error).wasCalledWith("MyException");
});
describe('bulk', function(){
it('should collect requests', function(){
scope.$xhr.bulk.urls["/"] = {match:/.*/};
@ -241,10 +252,10 @@ describe("service", function(){
scope.$xhr.bulk.flush(function(){ log += 'DONE';});
xhr.flush();
expect(xhrErrorHandler).wasCalled();
var cb = xhrErrorHandler.mostRecentCall.args[0].callback;
expect($xhrError).wasCalled();
var cb = $xhrError.mostRecentCall.args[0].callback;
expect(typeof cb).toEqual('function');
expect(xhrErrorHandler).wasCalledWith(
expect($xhrError).wasCalledWith(
{url:'/req1', method:'GET', data:null, callback:cb},
{status:404, body:'NotFound'});