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

app.js
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) {
  console.log(error.message);
}