【问题标题】:"Uncaught [object Object]" when throw and catch投掷和接球时出现“未捕获的 [object Object]”
【发布时间】:2016-04-12 07:51:12
【问题描述】:

我有一点 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

我还有很多其他的 throw 和 try/catch,但我没有这个问题 .. 你能解释一下为什么吗?

这是我的 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.");"给我一个 JS 错误.. 但是当我无法 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 类,适用于其他 throw :

function Exception(msg, fatal) {
    this.message = msg;
    this.fatal = fatal;

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

谢谢! :)

【问题讨论】:

    标签: javascript exception error-handling exception-handling


    【解决方案1】:

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

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

    【讨论】:

    • 哦,是的,我怀疑.. 但是,如何解决呢?使用带有 "async: false" 的 $.ajax 吗? ..这不是很干净..
    • @JorisBertomeu 就像我说的,在事件处理程序中处理失败,直接或通过调用另一个处理失败的函数。
    • 好的,好的!我可以使用 Promise 吗?
    • @JorisBertomeu 是的,你也可以使用 Promise 来处理成功或失败。
    • 非常感谢您的帮助!你能很快告诉我如何实现它吗? ..
    猜你喜欢
    • 2017-10-12
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多