4

我目前正在尝试确定处理 Durandal 应用程序中不同错误的最佳方法。我正在测试的一种情况是所需的模块不存在,即

define(['dummy'], function (Dummy) { return {}; });

哪里dummy不存在。我在下面的 main.js 文件中添加了以下内容requirejs.config({...})

requirejs.onError = function (err) {
    console.log('Global error', err);
};

但从这里永远不会记录错误。Durandals system.js 文件的控制台窗口中显示了 404 错误,并且还记录了错误消息:

未捕获的错误:无法加载路由模块(viewmodels/features/errorHandling/scriptNotFound/one)。详细信息:脚本错误:dummy

看起来该requirejs.onError函数永远没有机会被调用。我希望能够记录这些错误并通知用户有问题等。有人知道我会怎么做吗?

4

5 回答 5

2

一个常见的用例是使用 CDN 托管的库版本,但如果失败,请切换到本地加载文件:

requirejs.config({
    enforceDefine: true,
    paths: {
        jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min'
    }
});

//Later
require(['jquery'], function ($) {
    //Do something with $ here
}, function (err) {
    //The errback, error callback
    //The error has a list of modules that failed
    var failedId = err.requireModules && err.requireModules[0];
    if (failedId === 'jquery') {
        //undef is function only on the global requirejs object.
        //Use it to clear internal knowledge of jQuery. Any modules
        //that were dependent on jQuery and in the middle of loading
        //will not be loaded yet, they will wait until a valid jQuery
        //does load.
        requirejs.undef(failedId);

        //Set the path to jQuery to local path
        requirejs.config({
            paths: {
                jquery: 'local/jquery'
            }
        });

        //Try again. Note that the above require callback
        //with the "Do something with $ here" comment will
        //be called if this new attempt to load jQuery succeeds.
        require(['jquery'], function () {});
    } else {
        //Some other error. Maybe show message to the user.
    }
});

http://requirejs.org/docs/api.html#errbacks

于 2015-09-12T17:12:13.010 回答
1

我认为最好的方法是使用 Durandal 的system.error函数。只需在您的 appstart 中的某处放置类似的内容:

system.error = function(e) {
  //log the error
  console.debug(e);
  //redirect to a 404 view if you couldn't load module
  if (e.indexOf("Failed to load routed module") > -1) {
    location.href = '#404';
  }
  throw e;
};

在较大的项目中,您可能不想将整个应用程序捆绑到一个包中,以便您可以增量或按需加载应用程序的一部分,以减少初始加载时间,在这种情况下您希望能够处理加载错误。

于 2014-06-19T22:29:14.003 回答
0

布兰登是正确的。当你使用 Durandal 的路由器模块时,它会调用 Durandal 的 system.acquire,它会返回一个 promise,当 Require 完成加载模块时将调用该 promise。Require 的 errback 函数由 Durandal 提供,优先于 requirejs.onError。当 Durandal 遇到错误时,它会拒绝承诺,因此会调用 Durandal 路由器的失败函数。这个失败函数所做的就是调用 system.error。因此,在使用 Durandal 时,您可以通过提供自己的 system.error 版本来捕获所有 Require 模块加载错误。

于 2015-02-27T19:32:34.733 回答
-1

尝试将“onError”设为小写,如“onerror”(参见http://requirejs.org/docs/errors.html#scripterror)。

于 2014-01-02T20:29:34.820 回答
-1

可能不需要处理 AMD 依赖项加载错误,因为通常会在投入生产之前捆绑应用程序。

http://requirejs.org/docs/api.html#errors中描述的错误处理主要处理对外部资源的 jsonp 调用。此外,错误处理对 IE 有一些限制,因此可以解释您所看到的结果。

于 2014-01-03T09:56:58.970 回答