0

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

1
  • what happens if var jsonObject = JSON.parse(str); and str isn't JSON but is still the empty string? (for example if no data is sent with the request) Hint: you should have a try/catch around this so you handle bad/missing input here. Commented Sep 17, 2021 at 20:18

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.