admin管理员组文章数量:1414940
I am working with the node-instagram api (javascript). Occasionally, I get errors whenever I make a get request with the api. I want to display a particular error message when an ECONNRESET
exception is raised, and then display a generic error message for all the other types of exception. My code so far looks like this:
instagram.get('users/self/media/recent').then(data => {
console.log(data)
}).catch(err => {
console.log(err)
});
How can I alter the promise to make it also recognise ECONNRESET
exceptions and display a different error message when it catches them?
I am working with the node-instagram api (javascript). Occasionally, I get errors whenever I make a get request with the api. I want to display a particular error message when an ECONNRESET
exception is raised, and then display a generic error message for all the other types of exception. My code so far looks like this:
instagram.get('users/self/media/recent').then(data => {
console.log(data)
}).catch(err => {
console.log(err)
});
How can I alter the promise to make it also recognise ECONNRESET
exceptions and display a different error message when it catches them?
2 Answers
Reset to default 2If you put a breakpoint on your console.log(err)
and then inspect the err
object when you hit the breakpoint, you should be able to tell what property on the err
object tells you it was an ECONNRESET
. Trincot says it's code
. Then just use 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");
}
});
In that code, I'm rethrowing the error so the promise is rejected, on the assumption that you're returning the result of this chain to something that will make use of its rejection reason. If you're just doing the message right there in that catch
handler, then:
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
}
});
I would do Object.keys(err)
in your catch block, to see the keys the error object provides. One of those keys should have the value with details to identify the type of error.
So for EXAMPLE:
console.log(Object.keys(err)) ----> ['type','status','description']
if(err.type === 'ECONNRESET' && err.status === {code identifying it}){
// do something
}
本文标签: error handlingcatch a specific type of exception in a javascript promiseStack Overflow
版权声明:本文标题:error handling - catch a specific type of exception in a javascript promise? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745192639a2646983.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论