在javascript promise中捕获特定类型的异常?

知识就是力量

我正在使用node-instagram api(javascript)。有时,每当我使用api发出get请求时,都会出错。我想在引发ECONNRESET异常时显示特定的错误消息,然后为所有其他类型的异常显示通用错误消息。到目前为止,我的代码如下所示:

instagram.get('users/self/media/recent').then(data => {
    console.log(data)
}).catch(err => {
    console.log(err)
});

如何更改承诺以使其也识别ECONNRESET异常并在捕获异常时显示不同的错误消息?

TJ人群

如果在您的断点上放置了一个断点console.log(err),然后err在碰到断点时检查了该对象,那么您应该能够知道该err对象上的哪个属性告诉您它是一个ECONNRESET特林科特说是code然后只需使用if

instagram.get('users/self/media/recent').then(data => {
    console.log(data)
}).catch(err => {
    if (err.code === "ECONNRESET") {
        throw new Error("Specific error message");
    } else {
        throw new Error("Generic error message");
    }
});

在该代码中,我假设您要将此链的结果返回到可以利用其拒绝原因的某种东西上,因此我将该错误重新抛出以使承诺被拒绝。如果您只是在该catch处理程序中执行消息,则:

instagram.get('users/self/media/recent').then(data => {
    console.log(data)
}).catch(err => {
    if (err.code === "ECONNRESET") {
        // Show the specific error message
    } else {
        // Show the generic error message
    }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章