In Ukraine, we have tax API. It can sometimes be down, so it can be an error socket hang up. And I need to catch it because my app stops working. I've tried a lot, but it don't work.
import * as url from "url";
import * as http from "http";
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 it just stops. query function just don't catch errors. Only process.on catching error, but still it stops. I tried to like that:
process.on('uncaughtException', (err) => {
console.log(err);
startAsyncTasksFunction() // this is my main function
})
So, when there is uncaughtException, I just start main function. App don't stop and I have 2 startAsyncTasksFunction started and that's causing even more problems.
So, how can I catch it in query function. I need this to make some manipulations when tax is not responding. And catch error in query function, not globally.