JavaScript Node.js Basics 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);
});