how to handle proxy error in core-https in node js

Viewed 108

so am using core-https to do a Get request to a webstie , iam doing this get reqeust using a proxy by using this code :

const { HttpsProxyAgent } = require("https-proxy-agent");
const proxy = new HttpsProxyAgent(`http://user:pass@host:port`); 
https.get("https://www.google.com/",
{ agent: proxy },
(res) => {

  var body = "";
  res.on("data", function (chunk) {
    body += chunk;
    // console.log(body)
  });
  res.on("end", function () {
    }
  );
  
})

so sometimes the proxy would be invalid or expired , or even use a local-host for debugging using fiddler or Charles

const { HttpsProxyAgent } = require("https-proxy-agent");
const proxy = new HttpsProxyAgent(`http://127.0.0.1:8888`); // For Debugging
https.get("https://www.google.com/",
{ agent: proxy },
(res) => {

  var body = "";
  res.on("data", function (chunk) {
    body += chunk;
    // console.log(body)
  });
  res.on("end", function () {
    }
  );
  
})

and would also result an error if i forgot to open a proxy-debugger .

i tried doing it in this way :

  res.on("error" , function(e){
            console.log("an error have been occurred  ")
          })

but nothing seems to work

1 Answers

So i found the answer , it would be done like this

https.get(
  "https://www.google.com/",
  { agent: proxy },
  (res) => {
    var body = "";
    res.on("data", function (chunk) {
      body += chunk;
    });
    res.on("end", function () {
      // console.log(body)
    })

.on('error', function (e) {
   console.error("error");
}).end();
Related