JavaScript Node.js Basics Handling Errors in Node Handling Status Code Errors

some questions

const request = https.get(`https://teamtreehouse.com/${username}.json`, response => {
                            let body = "";
                            // Read the data
                            response.on('data', data => {
                              body += data.toString(); 
                            });
                           response.on('end', () => {
                              try {
                                // Parse the data
                                const profile = JSON.parse(body);}// INSTEAD OF THIS

                             //========= why cant we do this? ===================
                         response.on('end', () => {
                              try {
                                // Parse the data
                               body += data.toString(); 
                                const profile = JSON.parse(body);}//

like there might be some processing we might want to implement only when we actually get the chunk of data we get from the sv. is that all or is there some more to it?

as for my second question

// Problem: We need a simple way to look at a user's badge count and JavaScript points
// Solution: Use Node.js to connect to Treehouse's API to get profile information to print out

//Require https module
const https = require('https');

//Print Error Messages
function printError(error) {
  console.error(error.message);
}

//Function to print message to console
function printMessage(username, badgeCount, points) {
  const message = `${username} has ${badgeCount} total badge(s) and ${points} points in JavaScript`;
  console.log(message);
}

function getProfile(username) {
  try {
    // Connect to the API URL (https://teamtreehouse.com/username.json)
    const request = https.get(`https://teamtreehouse.com/${username}.json`, response => {
                            let body = "";
                            // Read the data
                            response.on('data', data => {
                              body += data.toString();
                            });

                            response.on('end', () => {
                              try {
                                // Parse the data
                                const profile = JSON.parse(body);                            
                                // Print the data
                                printMessage(username, profile.badges.length, profile.points.JavaScript);
                              }//here ; catch (error) {
                                printError(error);
                              }// and here ;
                            });

                          });
    request.on('error', printError);
  } catch (error) {
    printError(error);
  }
}

const users = process.argv.slice(2);
users.forEach(getProfile);

if you look at this code there's no closing ' ; ' on the try and catch and how can we know what is the scope of the try and catch. also is it necessary to use try and catch both together. i mean what would happen if you only use try and not catch or if you only use catch but not try.. i have commented it out in the 2nd code. another question the 'error' in the catch's paramater is the error from the global scope right? like same error as when we say error.message. id like to improve so feel free to suggest/give your opinion. thank you.

Steven Parker

// Problem: We need a simple way to look at a user's badge count and JavaScript points
// Solution: Use Node.js to connect to Treehouse's API to get profile information to print out

//Require https module
const https = require('https');
//Require http module for status codes
const http = require('http');
const profile =  require('./profile.js');

//Print Error Messages
function printError(error) {
  console.error(error.message);
}

//Function to print message to console
function printMessage(username, badgeCount, points) {
  const message = `${username} has ${badgeCount} total badge(s) and ${points} points in JavaScript`;
  console.log(message);
}

function getProfile(username) {
  try {
    // Connect to the API URL (https://teamtreehouse.com/username.json)
    const request = https.get(`https://teamtreehouse.com/${username}.json`, response => {
                            if (response.statusCode === 200) {
                              let body = "";
                              // Read the data
                              response.on('data', data => {
                                body += data.toString();
                              });

                              response.on('end', () => {
                                try {
                                  // Parse the data
                                  const profile = JSON.parse(body);                            
                                  // Print the data
                                  printMessage(username, profile.badges.length, profile.points.JavaScript);
                                } catch (error) {
                                  printError(error);
                                }
                              });
                            } else {
                                const message = `There was an error getting the profile for ${username} (${http.STATUS_CODES[response.statusCode]})`;
                                const statusCodeError = new Error(message);
                                printError(statusCodeError);
                            }
                          });
    request.on('error', printError);
  } catch (error) {
    printError(error);
  }
}






module.exports.getProfile = getProfile;

there are two catches used in this code. once in the if else statment and one catch after that why is that?

2 Answers

Steven Parker
Steven Parker
170,474 Points

The data chunks arrive with the "data" events. When you get the "end" event, it confirms that you now have all the data, but it doesn't pass any data itself. It takes both handlers to do the whole job.

The scope of the "try" is within the following block enclosed in braces. The "try" and "catch" statements always work together, neither one is useful by itself.

The "error" is like a function parameter — it is supplied by the exception. It's scope is limited to the "catch" block.

i see. thanks a lot as usual. btw one more thing why we dont close try code block and catch with ; ? also if you use

try{
//code 

}

//code 
catch (error) {
//code
}

will this still refer to the try mentioned above? so try only prevents from spittting out a stack error?

Steven Parker
Steven Parker
170,474 Points

Semicolons are used to end statements, but they are not used after code blocks as you might see after a "try", "catch", "if" and "else".

And there should not be any code between the "try" block and the "catch" that follows it.

Thanks a ton mate

Bilal Bajwa
Bilal Bajwa
4,028 Points

what is the answer to || means?

Steven Parker
Steven Parker
170,474 Points

For future questions, always start a fresh question of your own instead of asking a new question as an "answer".

But the "||" symbol is the logical "OR" operator, often used for testing more than one condition in a single expression. For more details, see this MDN page on Logical Operators.