简体   繁体   English

承诺-在deferred.reject期间出现包装错误

[英]Promise - wrapping error during deferred.reject

I'm trying to create a deferred wrapper using q.js such that I can wrap errors (strings) in a custom error class before they're passed back by the promise in then() or fail() . 我正在尝试使用q.js创建一个延迟包装器,这样我就可以将错误(字符串)包装在自定义错误类中, then()then()fail()的promise传回它们。 This is what I'm doing at the moment: 这是我目前正在做的事情:

var getDeferred = function() {

    var deferred = q.defer();

    var reject = deferred.reject;
    deferred.reject = function(error) {

        if (!(error instanceof MyErrorClass))
            error = new MyErrorClass(error)

        return reject.apply(deferred, arguments);
    }

    return deferred;
}

So the idea is that the user would do something like 因此,想法是用户将执行以下操作

var deferred = getDeferred();

deferred.promise.fail(function(err) {
    // err should now be instance of MyErrorClass and NOT a string
})

deferred.reject('A string error')

And expect to get MyErrorClass in the fail() handler, rather than the string passed to deferred.reject . 并且期望在fail()处理函数中获取MyErrorClass ,而不是传递给deferred.reject的字符串。

The above code works, but it's hardly ideal -- I know I shouldn't be monkey-patching deferred.reject. 上面的代码可以工作,但并不是很理想-我知道我不应该被延缓猴子补丁。 But is there a better way to do this? 但是有更好的方法吗?

It's prettier / more promise oriented like this : 这是更漂亮/更像这样的承诺:

var getDeferred = function() {

    var deferred = q.defer();

    deferred.promise = deferred.promise.then(null, function(error) {
        if (!(error instanceof MyErrorClass))
            error = new MyErrorClass(error)

        throw error
    }

    return deferred;
}

This way you just attach an error handler which will mutate any non MyErrorClass errors. 这样,您只需附加一个错误处理程序,该处理程序就会变异所有非MyErrorClass错误。 It seems like an odd use case in general though... 总的来说,这似乎是一个奇怪的用例...

Simply map over the fail case with then : 只需在与故障情况下映射then

actualPromise.then(null, function(error) {
    if (!(error instanceof MyErrorClass))
        error = new MyErrorClass(error)
    throw error;
})
.fail(function(err) {
    // err is now an instance of MyErrorClass and NOT a string
});

If you need a wrapper functionality, use a function that takes the actualPromise and calls then with the above code on it. 如果您需要包装器功能,请使用一个带有actualPromise的函数, then使用上面的代码进行调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM