简体   繁体   English

如何防止angularJS压缩脚本错误?

[英]How can I prevent angularJS from squelching script errors?

On my AngularJS sample project, I know that I have a service method which SHOULD throw a JavaScript error. 在我的AngularJS示例项目中,我知道我有一个服务方法,应该抛出JavaScript错误。

Using Firebug, I confirm that a JS error is thrown when resolving a promise from a $resource (TypeError: phone.images is undefined); 使用Firebug,我确认从$ resource解决承诺时抛出了JS错误(TypeError:phone.images未定义); but, the error never appears in the Firebug console. 但是,该错误永远不会出现在Firebug控制台中。

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. 理想情况下,我想在整个框架中对其进行修复,而不是为每个服务或资源调用添加特殊的错误处理代码。

You need to add the error callback to your get call: 您需要将错误回调添加到get调用中:

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 这是$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). 如果您想通过angular框架来一般性地处理AJAX请求的错误,那么您可能希望使用http拦截器 (请参阅“拦截器”部分)。 This kind of paradigm requires that all requests pass through your interceptor service to be handled in a generic fashion. 这种范例要求所有请求都以通用方式处理通过您的拦截器服务的所有请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM