"未捕获[对象对象]”;投掷和接球时

"Uncaught [object Object]" when throw and catch

本文关键字:对象 quot      更新时间:2024-05-16

我有一个小JS问题,当我在$.getJSON中抛出异常时,这个异常没有被父函数捕获,并且我有JS错误。。

Chrome的控制台返回给我:

Uncaught [object Object]
(anonymous function) @ ConfLoader.class.js:24
j                    @ jquery.min.js:2
k.fireWith           @ jquery.min.js:2
x                    @ jquery.min.js:4
(anonymous function) @ jquery.min.js:4

我还有很多其他的投掷和尝试/接球,我没有这个问题。。你能解释一下为什么吗?

这是我的ConfLoader"类":

var ConfLoader = {
    /* Attributes */
    apiToken : null,
    lavaBaseURL : null,
    apiURL : null,
    /* Init method */
    load : function(file) {
        $.getJSON(file, function(data) {
            if (data.apiToken)
                this.apiToken = data.apiToken;
            else
                throw new Exception("Token API (apiToken) not found into config file.");
            if (data.lavaBaseURL)
                this.lavaBaseURL = data.lavaBaseURL;
            else
                throw new Exception("Lava URL (lavaBaseURL) not found into config file.");
            if (data.apiURL)
                this.apiURL = data.apiURL;
            else
                throw new Exception("API URL (apiURL) not found into config file.");
        })
        .fail(function() {
            throw new Exception("File '"+file+"' not found.");
        });
    },
    /* Methods */
    getApiToken : function () {
        return this.apiToken;
    },
    getLavaBaseURL : function () {
        return this.lavaBaseURL;
    },
    getApiURL : function () {
        return this.apiURL;
    }
}

行"throw new Exception("File'"+File+"'not found。");"throw me a JS error。"。。但当我不能使用ConfLoader的方法"加载"时,我在这里发现了这个异常:

var Powers = {
    /* Attributes */
    confLoader : null,
    /* Methods */
    init : function(configFile) {
        try {
            this.confLoader = ConfLoader.load(configFile);
        } catch (e) {
            throw e;
        }
    },
    launch : function() {
        try {
        } catch (e) {
        }
    }
}

"Exception"类是一个自定义Exception类,适用于其他抛出:

function Exception(msg, fatal) {
    this.message = msg;
    this.fatal = fatal;
    this.isFatal = function() {
        return this.fatal;
    }
    this.getMessage = function() {
        return this.message;
    }
    return this;
}

谢谢!:)

$.getJSONfail处理程序是异步的,这意味着在其中抛出的异常不会传播到$.getJSON的调用方。不要抛出异常,而是尝试在fail处理程序中处理失败。

(您还会发现您的成功处理程序也有同样的问题。)