A
A
Alexander Smirnov2021-05-22 18:27:41
Node.js
Alexander Smirnov, 2021-05-22 18:27:41

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?

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


60a920daf08b2037425449.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Smirnov, 2021-05-23
@sasha-hohloma

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

To the following code
const tlsConnection = tls.connect({
    ...omit(opts, 'host', 'hostname', 'path', 'port'),
    socket,
    servername
});
tlsConnection.on('error', () => {
    return null;
});
return tlsConnection;

Perhaps it makes sense to dig more with the library in search of a more elegant solution. So far, it does not work even if throwing an error through . If I find another solution, I will write in the comments throw new Error()

T
tvbird, 2022-01-07
@tvbird

and that won't help?
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question