假设我有一个返回promise
的函数。返回的 promise 由外部函数检查,以决定如何处理 .fail()
条件。
function refreshTimeline() {
var promise = ajaxMethod1()
.then (function (data) {
return ajaxMethod2()
})
.then(function(json) {
//...
});
return promise;
}
function outerFunction() {
refreshTimeline
.then(function() {
//...
})
.fail(function(jqXHR, textStatus, errorThrown) {
// This will handle any errors in the chain *including* the refreshTimeline
});
}
我的问题是我需要在 refreshTimeline() 中抛出一个自定义业务异常,它应该被外部函数捕获,就像它捕获任何常规 Ajax 错误一样。目标是让 outerFunction 的 fail()
得到这个异常,并可能以一种特殊的方式处理它(也许它需要识别它)。
但以下不起作用:
function refreshTimeline() {
var promise = ajaxMethod1()
.then (function (data) {
return ajaxMethod2()
})
.then(function(json) {
if (someBusinessCondition(json) {
// throw custom exception
throw "MyException"; //JS gives "Uncaught" msg
}
});
return promise;
}
所以,我不想在 refreshTimeline()
中自己处理这个业务错误(因为这不是这个实用函数的工作——它只是将错误转发到下游),我想传播它向下到将处理的外部错误处理程序是一个常规的 .fail()
。这可能吗?
最佳答案
不是抛出异常,而是返回一个被拒绝的延迟/ promise 实例,并将您的字符串/异常/任何对象作为参数。
function refreshTimeline() {
var promise = ajaxMethod1()
.then (function (data) {
return ajaxMethod2();
})
.then(function(json) {
if (someBusinessCondition(json) {
// return your error as a rejected (failed) promise
return $.Deferred().reject("MyException");
}
});
return promise;
}
这将调用您的外部 .fail()
并将 "MyException"
作为第一个参数的值(您将其命名为 jqXHR
) .
关于javascript - jQuery Ajax promise : Throw Custom Exception and have it caught in outer fail(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48833723/