Reputation: 1984
I have a very simple question; I have a wrong endpoint and when I try the following code, it throws an exception
client.post("http://WrongEndPoint", [], function (data, response) {
console.log("data:", data, "response:", response.statusCode);
})
ERROR:
events.js:72
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT
at errnoException (net.js:905:11)
at Object.afterConnect [as oncomplete] (net.js:896:19)
So I try exception handler, but it is still not handeling the exception and I get the same exception:
try {
client.post("http://WrongEndPoint", [], function (data, response) {
console.log("data:", data, "response:", response.statusCode);
})
} catch (e) {
console.log("Error:", e)
}
Why can't I still handle the exception?
Upvotes: 0
Views: 273
Reputation: 716
JavaScript try/catch statement will not work in this case cause this operation performs asynchronously:
client.post("http://WrongEndPoint", [], function (data, response) {
console.log("data:", data, "response:", response.statusCode);
});
To catch it you should use approach like this
client.post("http://WrongEndPoint", [], function (data, response) {
console.log("data:", data, "response:", response.statusCode);
}).on('error', function(err){ console.log(err); });
But I'm not sure if it is correct cause I need to know which library do you use.
Upvotes: 1