0

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?

1
  • The error is thrown asynchrously. You'll need to check the docs of that function you're using on whether and how you can catch it (typically in a callback). Commented Jun 16, 2015 at 20:38

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

it is node-rest-client

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.