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

Tushar Mukherjee
Tushar Mukherjee
8,721 Points

I am always catching an exception when running my code even though it gives the right output

const https = require('https'); const api = require('./api.json'); const querystring = require('querystring');

function printData(jsonObject) {

var message = "Location: " + jsonObject.name + '\n' +
              "Current Temp: " + jsonObject.main.temp + 'C' + '\n' +
              "Max Temp: " + jsonObject.main.temp_max + 'C' + '\n' +
              "Min Temp: " + jsonObject.main.temp_min + 'C' + '\n' +
              "Humidity: " + jsonObject.main.humidity + '%' + '\n' +
              "Wind Speeds: " + jsonObject.wind.speed + 'm/s';
console.log(message);             

} function get(query) { const parameters = { APPID: api.key, units: 'metric' };

 const zipCode = parseInt(query);
if (!isNaN(zipCode)) {

  parameters.zip = zipCode + ',ind';

} else {

  parameters.q = query + ',ind';

}
const url = 'https://api.openweathermap.org/data/2.5/weather?'+ querystring.stringify(parameters);
console.log(url);

try{
const request = https.get(url,res =>{
    if(res.statusCode == '200'){
    var body = '';
    res.on('data',dataChunk =>{
        body += dataChunk.toString();
    });

    res.on('end',() =>{
        try{
            const jsonObject = JSON.parse(body);
            printData(jsonObject);
        }catch(error){
            console.log(error.message);
        }

    });
    }
    else{
        console.log('Error Code:' + res.statusCode);
    }
});

request.on('error',console.log(error.message));

}catch(error){
    console.log(error.message);
}

}

module.exports.get = get;


Output: C:\Users\tusha\Desktop>node app.js Los Angeles https://api.openweathermap.org/data/2.5/weather?//APPID=496b3c4f088e07e562ac68a7ceb0d621&units=metric&q=Los%20Angeles%2Cind error is not defined Location: Los Angeles Current Temp: 17.07C Max Temp: 18C Min Temp: 16C Humidity: 63% Wind Speeds: 2.6m/s


Note: See how catch block is always getting executed and prints 'error not defined'. Please Help me solve this problem. Thanks.

If you take a few minutes to fully explain what your objective is it will make it easier for people to help you. If you don't take some time to articulate your problem, why would anyone take their time to read a bunch of code without context?