为什么我的 catch() 处理错误事件?

Why does my catch() handle the error event?

有人可以解释为什么我的 catch() 不起作用吗?我得到

throw er; // Unhandled 'error' event
  ^

由此

const https = require('https');

const options = {
  hostname: 'github.comx',
  port: 443,
  path: '/',
  method: 'GET'
};

async function main() {
  options.agent = new https.Agent(options);
  const valid_to = await new Promise((resolve, reject) => {
    try {
      const req = https.request({
        ...options, checkServerIdentity: function (host, cert) {
          resolve(cert.valid_to);
        }
      });
      req.end();
    } catch (error) {
      reject(error);
    };
  });
  return valid_to;
};

(async () => {
  let a = await main();
  console.log(a);
  a = await main();
  console.log(a);
})();

更新

我在这里尝试 try/catch,但得到

TypeError: https.request(...).then is not a function

错误。

async function main() {
  options.agent = new https.Agent(options);
  const valid_to = await new Promise((resolve, reject) => {

    const req = https.request({
      ...options, checkServerIdentity: function (host, cert) {
        resolve(cert.valid_to);
      }
    }).then(response => {
      req.end();
    }).catch(rej => {
      reject(rej);
    });
  });
  return valid_to;
};

更新 2

这里的 promise 被移到了 try 块中,但我得到了同样的错误。

async function main() {
  options.agent = new https.Agent(options);
  try {
    const valid_to = await new Promise((resolve, reject) => {
      const req = https.request({
        ...options, checkServerIdentity: function (host, cert) {
          resolve(cert.valid_to);
        }
      });
      req.end();
    });
    return valid_to;
  } catch (error) {
    reject(error);
  };
};

request 是一个流,所以你应该在那里注册错误侦听器,拒绝,然后捕获错误:

async function main() {
  options.agent = new https.Agent(options);
  const valid_to = await new Promise((resolve, reject) => {

      const req = https.request({
        ...options, checkServerIdentity: function (host, cert) {
          resolve(cert.valid_to);
        }
      }).on('error', (error) => {
        console.error(error);
        reject(error);
    });
      req.end();

  });
  return valid_to;
};

(async () => {
  let a = await main().catch(err=>console.log(err));
  console.log(a);
})();