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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9032517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:26:19  来源:igfitidea点击:

Catching module loading errors and processing them

javascriptrequirejs

提问by Chin

I am trying to load some content using require.js. If the content doesn't exist I'd like to catch the error and notify the user.

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

In firebug I can see two errors:

在萤火虫中,我可以看到两个错误:

"NetworkError: 404 Not Found

“网络错误:404 未找到

...and then a few seconds later:

...然后几秒钟后:

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

My code resembles:

我的代码类似于:

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

How would one bind to requirejs events? Any idea?

如何绑定到 requirejs 事件?任何的想法?

回答by Louis

It is also possible to use errbacks to have customized error handling appropriate to the specific use of require. Errbacks are documented here http://requirejs.org/docs/api.html#errbacks. Basically, you can add to requirea function to be called if the load fails. It comes right after the function to be called if the load is successful.

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

Chin's case could be handled as:

Chin的案子可以这样处理:

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

Here's an example that tries loading from multiple places:

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

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);
    });
});

In this example onloadwould be the function called once the required code loads, and mode_pathis a string identifying the mode. What you see there is code attempting to load a mode module for an editor from 3 different locations. If mode_pathis foo, it will try to load foo, then ./modes/foo/fooand then ./modes/foo/foo_mode.

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

The example at requirejs.org shows how one might handle a case where they want to try multiple locations for a resource they want to make available with a well-known identifier. Presumably the entire code-base in that example requires jQuery by requiring "jquery". Whatever location jQuery happens to be located at, it becomes available to the whole code-base as "jquery".

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

My example does not care about making the mode known to the entire code-base through a well-known identifier because in this specific case there's no good reason to do so. The onloadfunction stores the module it gets into a variable and the rest of the code base gets it by calling a getMode()method.

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

回答by Shanimal

set the requirejs onError function:

设置 requirejs onError 函数:

requirejs.onError = function (err) {
    if (err.requireType === 'timeout') {
        // tell user
        alert("error: "+err);
    } else {
        throw err;
    }
};

If you want to setup an event you could bind to and trigger a global object. Such as:

如果你想设置一个事件,你可以绑定并触发一个全局对象。如:

$("body").bind("moduleFail",function(){
    alert("Handling Event")
});
requirejs.onError = function (err) {
    if (err.requireType === 'timeout') {
        $("body").trigger({type:"moduleFail",err:err})
    } else {
        throw err;
    }
};
require(["foo"],function(foo){
    alert("loaded foo" + foo)
})

回答by Gabriel Jürgens

Did you try to override the requirejs.onError like shown here?

您是否尝试像此处显示的那样覆盖 requirejs.onError ?

It worked for me after setting catchError as true like this:

像这样将 catchError 设置为 true 后,它对我有用:

require.config({catchError:true});

before calling any define()or require()functions.

在调用任何define()require()函数之前。

回答by anurag_29

You can use the requirejs.onError function as :

您可以将 requirejs.onError 函数用作:

requirejs.onError = function (err) {
    if (err) {
        //Reload
    } 
    else {
        throw err;
    }   
};

You can also use err.requireTypeto catch specific errors like timeouts

您还可以err.requireType用来捕获特定的错误,如超时