有没有调试失败的承诺的好方法?

时间:2019-09-07 15:36:58

标签: javascript promise

我在诺言的.then栏上有错字,诺言不断失败。我想我没有意识到是否有一种类型可以进入.catch。需要花大量的时间才能弄清楚这是个错误(继续假设,promise / async / etc调用有问题)。

有没有办法让JS告诉我“嘿,您的.then块有错误!”

代码

     searchAPI(name)
      .then(data => {
        // typo was LowerCase instead of toLowerCase
        let filtereddowndata = data
          .filter(item =>
            item.title.toLowerCase().includes(name.LowerCase())
          )
               etc etc

      })
      .catch(function() {
        console.log("no match found"); // kept going here.
      });

2 个答案:

答案 0 :(得分:2)

发送到.catch()的实际错误(您在代码中忽略了该错误)将为您提供一个很好的线索,说明为什么触发.catch()。使用类似这样的内容:

.catch(function(e) { 
    console.log(e);
    // any other processing code here
 });

我始终确保将实际错误记录在我的.catch()语句中,这样我就始终可以确切地知道为什么触发了该错误,并且不要盲目地假设代码是如何到达这里的。

这也是为什么当您没有任何.catch()时,node.js将其作为控制台警告(最终导致运行时错误)的原因,因为try/catch内置在.then()中如果您自己不在.catch()中公开错误,将会向您隐藏错误。


在这种情况下,上面的信息足以给您确切的错误。但是在其他情况下(出于调试目的),有时您可以在代码的更本地化区域周围插入自己的try / catch语句而受益。那也将向您显示.then()处理程序中发生的事情。

您可以运行此代码段以查看实际错误。

     // simulate your searchAPI() call
     function searchAPI() {
        return new Promise(resolve => {
            resolve([{title: "Superman"}, {title: "Spiderman"}]);
        });
    }
    
    let name = "Joe";
    
    searchAPI(name).then(data => {
        // typo was LowerCase instead of toLowerCase
        let filtereddowndata = data.filter(item =>
                item.title.toLowerCase().includes(name.LowerCase())
        );
    }).catch(function(e) {
        // console.log(e) will work with normal Javascript
        // here in a stackoverflow snippet where console.log has been replaced
        // you have to look at console.log(e.message) to see the error
        console.log("searchAPI failed - ", e.message);
    });

答案 1 :(得分:1)

我只能强调@jfriend的回答,您应该始终拒绝给出正确的错误消息并记录它们。

但是,了解承诺如何被拒绝以及哪些.catch()回调将从何处处理拒绝也很重要。可以better differentiate error origins not using the traditional .then(…).catch(…) pattern甚至tag each error with the function it's coming from

在您的情况下,错误消息“ 找不到匹配项”被放错了位置,因为它暗示searchAPI失败了,但这不是catch处理程序执行错误的唯一原因达到。相反,更好的模式是

function searchAPI(name) {
    …
    return Promise.reject(new Error("No match found"));
    //                              ^^^^^^^^^^^^^^^^ error message (or error code)
}   //                              thrown exactly where the error actually occurred

searchAPI(name).then(data => {
    let filtereddowndata = data.filter(item =>
        item.title.toLowerCase().includes(name.LowerCase())
    )
    …
}, err => { // <- second `then` argument
    console.log("Error from searchAPI", err);
});
// would now cause an unhandled rejection about the LowerCase method call

您当然可以将其与catch处理程序结合使用

searchAPI(name).then(data => {
    let filtereddowndata = data.filter(item =>
        item.title.toLowerCase().includes(name.LowerCase())
    )
    …
}, err => { // <- second `then` argument
    console.log("Error from searchAPI", err);
}).catch(err => {
    console.error("Error from promise callback", err);
});