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



有人能解释为什么我的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);
})();

更新

在这里,我在尝试/捕捉中尝试,但得到了

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);
})();

最新更新