Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Node.js Basics (2014) Building a Command Line Application Handling Parsing and Status Code Errors

James Barrett
James Barrett
13,253 Points

Few questions for clarification

Hello, World!

Newbie to Node.js here. I have a few questions that I need to clear up:

1.) What is the try/catch block beneficial here? Would the if/else on its own not suffice (view code below)?

    response.on('end', function() {
      if(response.statusCode === 200) {
        try {
            var profile = JSON.parse(body);
            printMessage(username, profile.badges.length, profile.points.JavaScript);
        } catch(error) {
            //Parse Error
            printError(error);
        }
      } else {
        //Status Code Error
        printError({
          message: "There was an error getting the profile for " + username + " (" + http.STATUS_CODES[response.statusCode] + ")"
        });
      }
    });

2.) Why are we sending an object and not a string to our printError(e) function that we defined earlier on (view code below)?

 printError({
   message: "There was an error getting the profile for " + username + " (" + http.STATUS_CODES[response.statusCode] + ")"
});

3.) Finally, what benefits have I encountered from using a Node so far (I am sure I will discover the power of Node when I begin doing more things, however I am intrigued to know the benefits of this console application so far to keep up the motivation!)?

Thanks, James.

2 Answers

David Olson
David Olson
8,690 Points

Hey James to answer your 2nd question.

When you defined the function printError you logged out error.message.

message here is the property on the built in error object that is passed in. Instead we want to pass in own OWN object. Therefore we create our own object with a message property which substitutes for the default object's message property.

you usually use a try catch if your code has the potential to crash so if try works then it works if try block doesnt work it wont crash and it will go to the catch block instead of crashing

James Barrett
James Barrett
13,253 Points

Okay, thanks. What about the other two questions I raised about why we are sending an object through and the benefits of Node (up to this very video) so far?