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?

Share Improve this question asked Jun 17, 2019 at 17:32 ipsa scientia potestasipsa scientia potestas 5311 gold badge8 silver badges23 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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
}

本文标签: error handlingcatch a specific type of exception in a javascript promiseStack Overflow