0

On my AngularJS sample project, I know that I have a service method which SHOULD throw a JavaScript error.

Using Firebug, I confirm that a JS error is thrown when resolving a promise from a $resource (TypeError: phone.images is undefined); but, the error never appears in the Firebug console.

How can I get the resource to 'fail fast' and propagate the error up the call stack?

Here is the service code:

var phonecatServices = angular.module('phonecatServices', ['ngResource']);

phonecatServices.factory('Phone', ['$resource',
  function($resource){
    return $resource('phones/:phoneId.json', {}, {
      query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
    });
  }]);

Here is the controller (which fails silently):

phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', 'Phone',
  function($scope, $routeParams, Phone) {
    $scope.phone = Phone.get({phoneId: $routeParams.phoneId}, function(phone) {
      //JS error SHOULD be thrown here:
      $scope.mainImageUrl = phone.images[0]; 
    });

    ...
}]);

I don't want the code to fail silently! How can I fix it?

Ideally, I would like to fix it throughout the framework, rather than putting in special error handling code for each service or resource call.

1 Answer 1

1

You need to add the error callback to your get call:

Phone.get({phoneId: $routeParams.phoneId}, function(phone){
  // Do Stuff with phone object
}, function(error) {
  alert("Y U NO RETURN PHONE?");
  // Handle error accordingly
});

Here is the documentation for $resource

If you'd like to generically handle errors for AJAX requests through the angular framework, then you'd probably like something like an http interceptor (Check the interceptors section). This kind of paradigm requires that all requests pass through your interceptor service to be handled in a generic fashion.

Sign up to request clarification or add additional context in comments.

1 Comment

Somewhere in the future, at a support desk far far away, there will be an IT help desk ticket entered: "When the user tries to view the phone details, they encounter an error message: Y U NO RETURN PHONE?"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.