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 2017 Handling Errors in Node Handling the Error Event in Node

I could not get the catch method to work properly.

I could follow along fine for the first half of the video and got a nice short error message. When I tried the catch method my error remained long though. I can't really figure out what went wrong there. Any help would be greatly appreciated!

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

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

try {
//function to print message to console
function printMessage(username, badgeCount, points){
const message = `${username} has ${badgeCount} total badges and ${points} points
in Javascript.`;
console.log(message)
}

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

                response.on('end', () => {
                    //Parse the data
                    const profile = JSON.parse(body);
                    //Print the data
                    printMessage(username, profile.badges.length, profile.points.JavaScript);
                });
            });
        request.on('error', error => console.error(`Problem with request ${error.message}`));
        } 
} catch (error) {console.error(error.message);} 

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

users.forEach(getProfile);

1 Answer

Steven Parker
Steven Parker
231,261 Points

This "try" is positioned outside of the function definition, so it is only effective while the function is being defined but not when the function is invoked.

To make it work while the function is running, it needs to be inside the function.

Thank you!