gpt4 book ai didi

javascript - 捕获模块加载错误并处理它们

转载 作者:IT王子 更新时间:2023-10-29 03:08:36 25 4
gpt4 key购买 nike

我正在尝试使用 require.js 加载一些内容。如果内容不存在,我想捕获错误并通知用户。

在 Firebug 中我可以看到两个错误:

"NetworkError: 404 Not Found

...几秒钟后:

var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#
Load timeout for modules: modules/messages/messages
http://requirejs.org/docs/errors.html#timeout

我的代码类似于:

require([path], function(content){
//need to catch errors as this will not be called;
});

如何绑定(bind)到 requirejs 事件?有什么想法吗?

最佳答案

也可以使用 errbacks 来定制适合 require 特定用途的错误处理。此处记录了错误 http://requirejs.org/docs/api.html#errbacks .基本上,您可以向 require 添加加载失败时要调用的函数。如果加载成功,它紧跟在要调用的函数之后。

Chin 的案例可以这样处理:

require([path], function(content){
//need to catch errors as this will not be called;
}, function (err) {
//display error to user
});

这是一个尝试从多个位置加载的示例:

require([mode_path], onload, function (err) {

if (mode_path.indexOf("/") !== -1)
// It is an actual path so don't try any further loading
throw new Error("can't load mode " + mode_path);

var path = "./modes/" + mode_path + "/" + mode_path;
require([path], onload,
function (err) {
require([path + "_mode"], onload);
});
});

在此示例中,onload 将是在所需代码加载后调用的函数,而 mode_path 是标识模式的字符串。您看到的代码试图从 3 个不同的位置为编辑器加载模式模块。如果 mode_pathfoo,它将尝试加载 foo,然后是 ./modes/foo/foo 然后./modes/foo/foo_mode.

requirejs.org 上的示例展示了人们可能如何处理这样一种情况:他们想要为他们想要使用众所周知的标识符提供的资源尝试多个位置。据推测,该示例中的整个代码库通过要求“jquery”来要求 jQuery。无论 jQuery 位于什么位置,它都可以作为“jquery”供整个代码库使用。

我的示例不关心通过众所周知的标识符使模式为整个代码库所知,因为在这种特定情况下没有充分的理由这样做。 onload 函数将它获取的模块存储到一个变量中,其余代码库通过调用 getMode() 方法获取它。

关于javascript - 捕获模块加载错误并处理它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9032517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com