JavaScript Node.js Basics Handling Errors in Node Organizing Your Code with require

Kevin Gates
Kevin Gates
14,640 Points

I get an undefined error first, then I get the proper response (200) right afterward. Any ideas as to why?


// 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
const profile = require('./profile.js');
const users = process.argv.slice(2)


//Require https module
const https = require("https");
// Require http module for status codes
const http = require("http");

//Print Error Messages
function printError(error) {

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

function get(username) {
  try {
    // Connect to the API URL (
    const request = https.get(`${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) {
      } else {
        const message = `There was an error getting the profile for ${username} (${http.STATUS_CODES[response.statusCode]})`;
        const statusCodeError = new Error(message); 
    }).on('error', printError(error))
  } catch (error) {

module.exports.get = get;

the code in node that I run is

node app.js romerican

I get back:

error is not defined
romerican has 108 total badge(s) and 2844 points in JavaScript

I've test it, the area that is first showing the undefined error is the catch could in the main function get. What I don't understand is why it first fails, then works...without being called twice.

Any insight is appreciated.

Gari Merrifield
Gari Merrifield
9,549 Points

I would look closely at what is actually happening in your app.js. slice of 2, then a foreach, would suggest that it may be getting called twice. I haven't dug into your code deeply, but that is where I would start, and maybe log what is actually getting into your users const.

1 Answer

Vitaly Khe
Vitaly Khe
7,155 Points

You have not passed error to a printError function in 44 string of your code. Pls include passing the error to it like :

    }).on('error', error => printError(error))