Answer the question
In order to leave comments, you need to log in
How to catch error in NodeJS?
Hello. I am writing a proxy checker to filter free proxy servers. The principle is this: if the test request is successful, then we add the address to the array, if the error is, we skip the address and take the next one.
But it is not possible to catch all errors, one constantly seeps past trycatch. And what is especially discouraging is that sometimes she can be caught, and sometimes she gets into uncaught errors and breaks everything.
I send requests to native for NodeJS https, I registered in all listeners and there is silence. It turns out that the error pops up in a different place altogether and manages to bypass the trycatch block. Update May 23 11:30
Instead of socks proxy tried http proxy based on this solution , did n't even help to catch this erroron('error')
console.log(error)
tlsConnection.on('error')
Question: why does this error pass by trycatch and how to catch it?
return new Promise((resolve, reject) => {
const httpsOptions: RequestOptions = {
hostname: ProxyURLs.checkIP,
port: 443,
method: HttpMethods.post,
headers: {
'Content-Type': 'application/json',
},
agent: new SocksProxyAgent({
host: proxy.ip,
userId: proxy.login,
password: proxy.password,
port: proxy.port,
type: 5,
timeout: Seconds.two,
}),
};
const req = https.request(httpsOptions, (res) => {
res.on('error', reject);
res.on('data', (data) => {
const parsed = JSON.parse(data);
resolve(parsed);
});
});
req.on('error', reject);
req.end();
});
Answer the question
In order to leave comments, you need to log in
The problem turned out to be inside the SocksProxyAgent library . I don’t remember where I read it, but somewhere on GitHub they wrote that such an error falls out as uncaught, because the handler on the error event for tls.connect
.
Finally fixed it
return tls.connect({
...omit(opts, 'host', 'hostname', 'path', 'port'),
socket,
servername
});
const tlsConnection = tls.connect({
...omit(opts, 'host', 'hostname', 'path', 'port'),
socket,
servername
});
tlsConnection.on('error', () => {
return null;
});
return tlsConnection;
throw new Error()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question