I have a NodeJS server and I use IPInfo.io to check which country visitors come from. I get an error from the response of IPInfo.io that crashes the server:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at IncomingMessage.<anonymous> (~/server/node_modules/node-ipinfo/dist/src/ipinfoWrapper.js:93:43)
This is the only place where I use IPInfo:
const IPinfo = require('node-ipinfo');
async function getVisitor(req) {
// ....
console.log(req.originalUrl, " :: ", req.ip, " :: ", ua);
let ip = req.ip;
if (ip.startsWith("::ffff:")) {
ip = ip.replace(new RegExp("^::ffff:"), '');
}
console.log("Requesting IP information for " + ip);
let countryCode;
let ipinfo = new IPinfo(config.ipinfo);
try {
let info = await ipinfo.lookupIp(ip);
countryCode = info.countryCode;
} catch (e) {
console.error("n# IP Info error for ip address: " + ip + " (" + req.ip + ")")
countryCode = undefined;
}
}
And I’m confused why the error escapes the try-catch. But this is the only place where I use IPInfo.
This works fine most of the time, but sometimes I get an error that crashes the server. Here is the relevant part of the error log, where the server takes about 4 seconds to restart:
[2024-06-18T03:08:59.465Z] SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at IncomingMessage.<anonymous> (~/server/node_modules/node-ipinfo/dist/src/ipinfoWrapper.js:93:43)
at IncomingMessage.emit (node:events:513:28)
at IncomingMessage.emit (node:domain:489:12)
at emitCloseNT (node:internal/streams/destroy:138:10)
at processTicksAndRejections (node:internal/process/task_queues:82:21)
[2024-06-18T03:09:03.510Z]
# HTTPS server started
and of the output log:
[2024-06-18T03:08:59.222Z] / :: 147.185.132.177 :: Expanse, a Palo Alto Networks company, searches across the global IPv4 space multiple times per day to identify customers' presences on the Internet. If you would like to be excluded from our scans, please send IP addresses/domains to: [email protected]
[2024-06-18T03:08:59.228Z] Requesting IP information for 147.185.132.177
[2024-06-18T03:09:03.341Z]
# server starting...
I read Nodejs exception escapes the try/catch block and I think my problem is different because I have an await
in the request for IPInfo.
Why does the error escape the try-catch block, or how can I trace the source of the error?