【问题标题】:Order of thrown errors?抛出错误的顺序?
【发布时间】:2017-12-15 05:22:48
【问题描述】:

我有一个函数,当发生错误时(例如“超时”)应该抛出一个错误,我在承诺链的末尾捕获。

var createOrder = function (id) {
    Utility.toggleProgressBar();
    return $.ajax({
        url: 'http://' + AppVar.ServerUrlWithPort + '/restapi/CreateOrder',
        data: JSON.stringify({
            'SessionId': AppVar.SessionId,
            'Idrmtreq': id
        }),
    }).then(function (response) {
        if (response.ResultCode === '0') {
            return response;
        } else {
            throw new Error($.i18n('Error-RetrivingDataProblem'));
        }
    }).fail(function (x, t, m) {
        if (t === "timeout") {
            throw new Error($.i18n('Error-Timeout')); //code reaches here, where Chrome debugger says that this error was left Uncaught
            //for the record, I checked whether the translation function could be the problem and it doesn't work even when I do 'throw "timeout";'
        } else {
            throw new Error($.i18n('Error-ConnError'))
        }
    }).catch(function (error) {
        //error == {"readyState":0,"status":0,"statusText":"timeout"}
        ErrorManager.displayError(error);
        return;
    }).always(function () {
        Utility.toggleProgressBar();
    })
}

具体来说,我遇到了超时问题。代码到达投掷。我扔的球实际上没有被抓住,但有些东西被扔了。 Catch 捕获包含此 Object {"readyState":0,"status":0,"statusText":"timeout"} 的错误。

我不明白。扔什么?

【问题讨论】:

  • 你使用的是哪个 jQuery 版本?
  • .fail 没有做你认为的事情
  • $.ajax 正在抛出它。
  • @Jonasw 那么,它会延迟抛出它吗?正如我所说,我可以一直断点到实际的 throw 并抛出它,此时我的 catch 将捕获 ajax 错误?这很奇怪。
  • 似乎catch 是在promise 被拒绝时触发的,而不是在抛出错误时触发的。我猜你还是得用try{ }catch(err){ } 结束

标签: javascript jquery jquery-deferred jquery-3


【解决方案1】:

切勿使用donefail。它们不链接(也不捕获异常)。

fail() 调用返回原始承诺,在您的情况下,这意味着原始错误刚刚落空。您可以改用.catch(),但请注意chaining .then(…).catch(…) 也可以处理Error-RetrivingDataProblem。相反,你会想要使用

return $.ajax({
    url: 'http://' + AppVar.ServerUrlWithPort + '/restapi/CreateOrder',
    data: JSON.stringify({
        'SessionId': AppVar.SessionId,
        'Idrmtreq': id
    }),
}).then(function (response) {
    if (response.ResultCode === '0') {
        return response;
    } else {
        throw new Error($.i18n('Error-RetrivingDataProblem'));
    }
}, function(x, t, m) { /*
^^^ */
    throw new Error($.i18n(t === "timeout" ? 'Error-Timeout' : 'Error-ConnError'));
}).catch(function (error) {
    ErrorManager.displayError(error);
    return;
})

【讨论】:

  • 效果很好。谢谢你。将我的思想包裹在承诺上比我预期的要难。
猜你喜欢
  • 2018-02-11
  • 2015-03-04
  • 1970-01-01
  • 1970-01-01
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
相关资源
最近更新 更多