Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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?