A
A
Arthur Lomakin2022-02-11 21:30:53
JavaScript
Arthur Lomakin, 2022-02-11 21:30:53

How to handle socket hang up error?

In Ukraine, we have a tax API. Sometimes the server hangs up, so it's a socket hang up - that's fine. And I need to handle this error because my program stops. I tried several options but nothing works.

export function query(method, toUrl, headers, payload, cb) {
    try {
        let parsed = url.parse(toUrl);
        let req = http.request({
            host: parsed.host,
            path: parsed.path,
            headers: headers,
            method: method,
        }, res => {
            let chunks = [];
            res.on("data", chunk => {
                chunks.push(chunk);
            });
            res.on("end", () => {
                cb(Buffer.concat(chunks));
            });
            res.on("error", () => {
                console.log("SOCKET ERR!!!");
                req.end();
                cb(null);
            });
        });
        req.on("error", e => {
            console.log("SOCKET ERR!!!");
            req.end();
            cb(null);
        });
        req.write(payload);
        req.end();
    }
    catch(e) {
        console.log("Error in query function: " + e.message);
    }
}

I also tried this:
process.on('uncaughtException', (err) => {
    console.log(err);
})

But the program throws an error and just stops. the function queryjust doesn't catch errors. Only process.oncatches the error, but still stops.
Also tried this:
process.on('uncaughtException', (err) => {
    console.log(err);
    startAsyncTasksFunction() // this is my main function
})

That is, when it throws out uncaughtException, I just run the main function of the program. The app won't stop and I have 2 running startAsyncTasksFunctionwhich causes even more problems.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artur Lomakin, 2022-02-17
@arthurlomakin

Solved the problem with PM2 Manager. In short, I will switch to .NET, since this option does not suit me anyway.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question