简体   繁体   中英

using try-catch for https but don't catch any error

am using HTTPS to fetch data from a website, what I want to do is to catch any error that could happen, but the thing is that it catches nothing so this is my main code

test = async() => {
  console.log("Hellow")
  now = new Date();
  const https = require("https");
  https.get("website",{ agent: proxyy },
    (res) => {
      var body = "";
      res.on("data", function (chunk) {
        body += chunk;
      });
      res.on("end", function () {
        var resp = JSON.parse(body);
        data_wanted = resp.data
        const desiredItem = data_wanted.find((item) =>
          item.name.includes("data")
        );
        console.log(desiredItem)
      });
    }
  );
};

I tried multiple ways for the error catch like this

async function run() {
  try {
     await test();
  } catch (error) {
    console.log(error)
  }
  

and also this way

async function f() {
  try{
  run = await test()
}catch(e){
  console.log("Hello world")
}

}

it tried using the try-catch inside the function but also didn't works, my best guess that the try-catch is being executed before the function finish fetching

EDIT 1 : so my real intention is to do a while loop which keep trying until there is not error

const https = require('https');

https.get('https://encrypted.google.com/', (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });

}).on('error', (e) => {
  console.error(e);
});

https://nodejs.org/api/https.html#https_https_get_options_callback

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM