如何处理Requirejs中的404错误

时间:2014-01-02 16:43:10

标签: requirejs durandal durandal-2.0

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

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

其中dummy不存在。我已将以下内容添加到requirejs.config({...})下面的main.js文件中:

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

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

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

看起来requirejs.onError函数永远不会被调用。我希望能够记录这些错误并通知用户存在问题等。任何人都知道我会怎么做?

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;
};

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

答案 2 :(得分:0)

布兰登是对的。当您使用Durandal的路由器模块时,它会调用Durandal的system.acquire,它返回一个Prom,当Require完成加载模块时将会调用该promise。要求的错误功能由Durandal提供,优先于requirejs.onError。当Durandal收到错误时,它会拒绝承诺,因此会调用Durandal路由器的失败功能。所有这些失败功能都是调用system.error。因此,在使用Durandal时,您可以通过提供自己的system.error版本来捕获所有Require模块加载错误。

答案 3 :(得分:-1)

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

答案 4 :(得分:-1)

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

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