Ganzu
Ganzu

Reputation: 18

APP Crashing in Node JS if the json request is undefined

I am new to Node JS and I had done a lot of research and couldnt find any solution for the same. This is my code below

if(msg.body == 'Track ' + slug){
const str = msg.body;
const slug = str.substring(str.indexOf("Track") + 6); // 01-2020
var http = require('https');
var options = {
host: 'example.com',
path: '/example/example?id=' + slug
};

callback = function(response) {
var str = '';

response.on('data', function (chunk) {
str += chunk;
});

response.on('error', (err) => {
    msg.reply('Error!');
  })


response.on('end', function () {
var jsonObject = JSON.parse(str);

msg.reply('Current status of ' + slug + ': ' +  jsonObject[0]['body']);
});

}

http.request(options, callback).end();

}

So if I enter Track and a value the value will be captured and then sent in the json request. The json request very much works unless there is an error where the app crashes. This becomes a very big problem. So If I enter the wrong value then the app crashes saying undefined in the log. I want it to msg.reply the error instead of the app crashing. Please help me out. Thank you in advance

Upvotes: 0

Views: 629

Answers (2)

jasonhargrove
jasonhargrove

Reputation: 61

Here are some helpful examples for node

Handling Errors

try {
  //lines of code
} catch (e) {
  msg.reply('Error!');
  console.log(e);
}

Handling uncaught exceptions

process.on('uncaughtException', err => {
  console.error('There was an uncaught error', err)
  process.exit(1) //mandatory (as per the Node.js docs)
})

Exceptions with promises

doSomething1()
  .then(doSomething2)
  .then(doSomething3)
  .catch(err => console.error(err))

With async functions

async function someFunction() {
  try {
    await someOtherFunction()
  } catch (err) {
    console.error(err.message)
  }
}

Learn more here https://nodejs.dev/learn/error-handling-in-nodejs

Upvotes: 0

Garett Friesen
Garett Friesen

Reputation: 69

Like what commenter Joe says you should wrap your response code in a try/catch block. That will let you print out the error message properly.

try {
  .. code youre expecting to hopefully not crash ..
} catch (error) {
  msg.reply('Error!', error);
}

Upvotes: 2

Related Questions