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 Errors in Node

Michael Lawinger
Michael Lawinger
33,581 Points

On a new line use the on method to listen for the error event. Pass in a callback function with one parameter of error.

On a new line use the on method to listen for the error event. Pass in a callback function with one parameter of error.

app.js
const https = require("https");

var request = https.get("https://teamtreehouse.com/chalkers.json", response => {
  console.log(response.statusCode);
});

request.on('error' error(error) );

2 Answers

Loris Guerra
Loris Guerra
17,536 Points

The challenge first asks you to listen for the 'error' event

request.on("error");

Then to pass a callback function (which here is simply a function passed as second argument to the 'on()' method)

request.on("error", function(){} );

This callback function will get called with an 'error' object as argument

request.on("error", function(error){} );

Finally, inside the callback you've just defined, you log to the screen the 'error.message' property, which is a string. To do so, they suggest you to use 'console.error()' instead of 'console.log()', but these 2 methods work very similar each other.

request.on("error", function(error){
  console.error(error.message);
});

Hope this helps! :)

First task: just assign the value returned from the function to the request variable

const https = require("https");
const request = https.get("https://teamtreehouse.com/chalkers.json", response => {
  console.log(response.statusCode);
});

Second task: use the "on" method to retrieve the error, then print out with "console.error"

request.on('error', error => {
  console.error(error.message);
});