Can someone explain why my catch()
doesn’t work? I get
throw er; // Unhandled 'error' event ^
from this
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); })();
Update
Here I try withiy try/catch, but get
TypeError: https.request(...).then is not a function
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); } }).then(response => { req.end(); }).catch(rej => { reject(rej); }); }); return valid_to; };
Update 2
Here the promise is moved inside the try block, but I get same 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); }; };
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
request
is a stream, so you should register error listener there, reject, and then catch the 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); })();
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0