在其初始化器对象中捕获异常

catch exception in its initializer object

本文关键字:捕获异常 对象 初始化      更新时间:2023-09-26

我有一个Ajax对象,在一些其他对象中用于加载'Json'文件。

我需要在初始化对象中捕获404 'Not found'抛出的异常,但我不能这样做,它总是给我:

Uncaught Exception: *********

这里有一段代码:

_ajax_params.xmlhttp.onreadystatechange = function() {
    if (_ajax_params.xmlhttp.readyState==4 && _ajax_params.xmlhttp.status==200) {
        _ajax_params.response = _ajax_params.xmlhttp.responseText;
        if (typeof afterClosure == 'function') {
            afterClosure(_ajax_params.response);
        }
        COMMON.always(_ajax_params.response);
    } else if (_ajax_params.xmlhttp.status== 404) {
        throw 'File not found';
    }
};

初始化对象:

try {
   Base.include.json(url, 1);
} catch (e) {
   console.error(e);
   Base.include.json(url,2);
}

我试图重新抛出异常,但我得到相同的。

您可以在try..catch块中定义回调,但函数在该块之外执行(即。当事件被触发时)。这意味着在回调中发生的异常不会被外部块捕获。

下面是一个动作差异的演示。

考虑用Base.include.json(url,2)代替throw 'File not found';

此外,除非您已经知道readyState4,否则您不应该真正检查status,但这是一件小事。