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?
If 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With