JavaScript Node.js Basics Handling Errors in Node Handling Parsing Errors with try and catch

Jiho Song
Jiho Song
16,469 Points

What about next try syntax?

// 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

// Connect to the API URL (
// Read the data
// Parse the data
// Print the data
const https = require('https');

function printMessage(username, badgeCount, points) {
          const message = ` ${username} has  ${badgeCount} total badge(s) and ${points} points in JavaScript `;

function getProfile(username) {
  try {
        const request = https.get(`${username}.json`, response => {
                                 let body = "";
                                  response.on('data', data => {
                                    body += data.toString();
                                  response.on('end', () => {
                                    const profile = JSON.parse(body);
                                   printMessage(username, profile.badges.length, profile.points.JavaScript);
                                  } catch(error) {

    request.on('error', error => console.error(`Problem with requrest ${error.message}`));
}catch (error) {console.error(error.message);

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

as you can see the code above, there are two different try and catch, which i expected it to perform individually, however it works only once with first one. Does try and catch only works one time with the first catching and ignoring with further catching?

I'm bit confused with try and catch

fixed code formatting

1 Answer

Craig Peckett
Craig Peckett
10,531 Points

When the code throws an error it will stop running, therefore it will only log first error it comes across. That way you can go and fix the error and run your code again fixing one problem at a time instead of trying to do multiple errors at once.