我目前正在尝试确定处理 Durandal 应用程序中不同错误的最佳方法。我正在测试的一种情况是所需的模块不存在,即
define(['dummy'], function (Dummy) { return {}; });
在哪里
dummy
不存在。我已在 requirejs.config({...})
正下方的 main.js 文件中添加了以下内容:requirejs.onError = function (err) {
console.log('Global error', err);
};
但从这里永远不会记录错误。 Durandals system.js 文件的控制台窗口中显示了 404 错误,并且还记录了错误消息:
Uncaught Error :无法加载路由模块(viewmodels/features/errorHandling/scriptNotFound/one)。详细信息:脚本错误:dummy
它看起来像
requirejs.onError
函数永远没有机会被调用。我希望能够记录这些错误并通知用户有问题等。有人知道我会怎么做吗?
最佳答案
A common use case for this is to use a CDN-hosted version of a library, but if that fails, switch to loading the file locally:
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
关于requirejs - 如何处理来自 Requirejs 的 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20887510/