javascript - 使用 promise 链进行错误处理

标签 javascript error-handling promise

我有一连串的 promise

promisedStep1()
    .then(promisedStep2)
    .then(promisedStep3)
    .then(promisedStep4)
    .then(function (value4) {
        // Do something with value4
    })
    .catch(function (error) {
        // Handle any error from all above steps
    });

我需要知道我在哪一步出错了。

如果我在每个 promise 的步骤中添加 catch

promisedStep1()
    .catch(function(){
        throw {code: 1}
    })
    .then(promisedStep2)
    .catch(function(){
        throw {code: 2}
    })
    .catch(function (error) {
        console.log('error in ', error.code);
    });

code 始终为 2,因为它从第一个捕获到第二个捕获。

处理此类错误的技巧是什么?

编辑

找到了方法:

function promisedStep1Wrapper(){
    return promisedStep1()
        .catch(function(){
            throw {code: 1};
        });
}

function promisedStep2Wrapper(){
    return promisedStep2()
        .catch(function(){
            throw {code: 2};
        });
}

promisedStep1Wrapper()
    .then(promisedStep2Wrapper)
    .catch(function(err){
        console.log(err.code);
    });

这样可以吗,或者有更好的解决方案吗?

最佳答案

Is this ok?

是的,完全可以。

or is there any better solution?

“更好”我不知道,但肯定还有其他。一种方法是仅处理您期望的那些错误 - 上一步中的错误,并重新抛出其他所有错误。像 Bluebird 这样的一些库确实有专门的辅助函数来实现这种绝对优越的方法。它基本上看起来像这样:

promisedStep1() // throws Step1Error
.catch(function(err) {
    if (!(err instanceof Step1Error)) throw err;
    throw {code: 1};
})
.then(promisedStep2) // throws Step2Error
.catch(function(err) {
    if (!(err instanceof Step2Error)) throw err;
    throw {code: 2};
})
.catch(function(error) {
    if (!("code" in error)) throw error; // duck typing
    console.log('error in ', error.code);
})
.catch(function(error) {
    console.error("completely unexpected:", error);
});

另一种方法是嵌套并使用第二个 then 回调进行专用错误处理 - 请参阅 When is .then(success, fail) considered an antipattern for promises?.then().catch() 的区别。使用它,您的代码将如下所示

promisedStep1()
.then(function(res) {
    return promisedStep2(res)
    .then(function(res) {
        // do something
        return res;
    }, function(err) { // error in promisedStep2
        throw {code: 2};
    });
}, function(err) { // error in promisedStep1
    throw {code: 1};
})
.catch(function(error) {
    if ("code" in error)
        console.log('error in ', error.code);
    else
        console.error("completely unexpected:", error); // from "do something"
});

这种方法效果很好,可以对附加处理程序进行细粒度控制,干净地分离成功和错误路径,但在语法上有点困惑。

关于javascript - 使用 promise 链进行错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32603630/

相关文章:

Angular,错误拦截器,在不同的 url 上重试原始请求

javascript - Promise.race 在一个 Promise 被拒绝后继续运行

javascript - 突出显示字符串中的文本

php - PHP将不会报告错误

javascript - 如何减少 javascript/jquery 更改事件的延迟?

ios - 如何更改Parse系统错误代码?

javascript - 从方法返回的 Promise 未定义

JavaScript:顺序迭代 Promise 函数

javascript - ajax php 获取行值

javascript - 按\n 字符分割似乎不起作用