NodeJS troubleshooting help

Hi all,

I’m not very good at JavaScript coding. I spent some time on the weekend coding up a simple app that does REST polling every minute (gathering arrival times from a bus stop, via an open API), and publishing the values via MQTT onto Solace broker using MQTT.js.

Now… I’ve been running the program using nohup node test.js > output.txt 2>&1 & and after several hours it just terminates. No error messages or anything in the output.txt log file (I have both stdout and stderr redirecting). And I have an error hander on the client object, so I don’t think it’s an MQTT error. So I have no idea why it’s just terminating? Is there some NodeJS debugging things I can do, to see why it terminated unexpectedly?? Thanks!!

Is there a way out of your loop that doesn’t create an error condition? Maybe it’s just hitting that? With Javascript, it almost always is about async race conditions.

Node may have crashed due to unhandled rejections (a possibility!). If you can instrument your code with a handler, at least you might know why it crashed (if at all). Refer to https://blog.heroku.com/best-practices-nodejs-errors for more details.

Curious to know, are you using setinterval() for your repeated REST request? You can perhaps make it simpler

async function getArrivalTime() {
  // do your REST fetch here. You can use whatever library so for example I am using fetch from node-fetch here 
  const baseURL = `API`;
  let res = await fetch(baseURL).catch((err) => {
    throw new Error(`Error fetching content from ${baseURL}. ${err}`);
  });

  if (!res.ok) {
    throw new Error(`Response status from ${baseURL}: ${res.status}`);
  }
  // manipulate your response
  // let body = await res.text();
  // Content body from github is base64 encoded
  // return Base64.decode(JSON.parse(body).content);
}

setInterval(() => {
  let content = await getArrivalTime();
  // Console logs, write to file...etc
  // MQTT publish to broker
}, 1000);
// Note this does it every 1 second!

and then just run your file node file.js

Hi guys, thanks for the comments.

I have added some extra try / catch blocks around various logic. There isn’t much to my program, so hopefully that catches something. And added a process.on('uncaughtException') as that blog Giri suggested, so hopefully this next run turns up something.

Thanks Tamimi. My code does a fetch(url) .then(reponse => response.json) .then(json => { some code }); And the whole thing is wrapped in a try / catch block. So no specific error handling on the fetch like yours above, no await… you have two separate error handling checks. Wondering if I should add those?

My error handling logic is thin the fetching; if the endpoint is malformed and if the return is not 200 OK. I suspect that your error is in a fetch block since its failing silently, and almost most fetch related issues raise errors. Tho you can also add that and check it out