JGleason
JGleason

Reputation: 3946

How do I catch "Error: connect ECONNREFUSED" in Node without Node dying?

I have the following code...

http.get({
    host: ipAddress,
    port: 1199
}, (response)=>{
   ...
   response.on("error", ()=>{...});
});

Now I know that ipAddress is null and there is nothing running on 1199 so I expect an error.

Error: connect ECONNREFUSED 127.0.0.1:1199

However, when I wrap in a try catch it does not catch the error so...

try{
    http.get({
        host: ipAddress,
        port: 1199
    }, (response)=>{
       ...
       response.on("error", ()=>{...});
    });
} catch(ex){
   console.log("error");
}

Instead of seeing error in the log I still get...

Error: connect ECONNREFUSED 127.0.0.1:1199

So how do I capture the error?

Upvotes: 0

Views: 550

Answers (1)

Dan D.
Dan D.

Reputation: 74655

Put the error listener on the ClientRequest returned by the http.get call.

http.get({
    host: ipAddress,
    port: 1199
}, (response)=>{
   ...
}).on("error", ()=>{...});

https://nodejs.org/api/http.html#http_class_http_clientrequest https://nodejs.org/api/http.html#http_http_get_options_callback

Upvotes: 2

Related Questions