¿Alguien puede explicar por qué mi catch() no funciona? yo obtengo
throw er; // Unhandled 'error' event ^de esto
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); })();Actualizar
Aquí trato de intentar/atrapar, pero obtengo
TypeError: https.request(...).then is not a functionerror.
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; };Actualización 2
Aquí la promesa se mueve dentro del bloque de prueba, pero obtengo el mismo error.
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); }; };La request es una transmisión, por lo que debe registrar el detector de errores allí, rechazarlo y luego detectar el error:
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); })();