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 Using try and catch

Issue with node js code

var username = "chaklers123"; var http = require("http");

function printMessage(username, badgecount, points)
var message = username+" has the badge count" + badgecount + " total points" + points ; console.log(message); } var request = http.get("http://www.teamtreehouse.com/chalkers123.json", function(response){ var body = ''; response.on('data', function(chunk) { body +=chunk;
}); response.on('end', function(){
if (response.statusCode == 200) { var profile = JSON.parse(body); printMessage(username, profile.badges.length, profile.points.Javascript); } else { console.log(error.message); }

}); });

getting the following error can someone help in resolving the issue.

ReferenceError: error is not defined
at IncomingMessage.<anonymous> (/home/treehouse/workspace/app.js:21:23)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)

var jsonString = 'This is not a JSON String';
var jsonObject = JSON.parse(jsonString);

1 Answer

Rich Zimmerman
Rich Zimmerman
24,063 Points

You want to use a try catch block to catch the error when there is one. Without it, the error object is not defined. Try this

try {
 // Your http request and corresponding functions
} catch (error) {