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 Status Code Errors

What for new Error Object?

Hi, what for we use new Error if we can only console.log There was en error getting the profile for ${this.user}, ${response.statusCode}; and receive some result?

Second question: I did not understand anything with processing http error.

1 Answer

Kevin Gates
Kevin Gates
15,053 Points

So you're asking why we have this:

const message = `There was an error getting the profile for ${username} (${http.STATUS_CODES[response.statusCode]})`;
const statusCodeError = new Error(message); 
printError(statusCodeError);

The answer is that the printError function essentially requires an error object because the code looks for the "message" property inside of the error object. See here:

//Print Error Messages
function printError(error) {
  console.error(error.message);
}

Therefore, he is creating the new Error(message) object so things are properly scaffolded to be later parsed correctly in the printError function.


Your second question has to do with processing the http error. Well, Node can import different libraries/modules to expand it's functionality.

In this case, the module is the http module. One of the things this module can do is take in status codes (404, 201, 307, etc.) and interpret the for human readers (see here: https://nodejs.org/api/http.html#http_http_status_codes ). So instead of saying "404", it will say "Not Found", etc.

Doron Geyer
seal-mask
.a{fill-rule:evenodd;}techdegree
Doron Geyer
Full Stack JavaScript Techdegree Student 13,897 Points

Along the same lines as above you could just have used

 printError(new Error(`there was a problem finding ${username}`));

Instead of Making multiple variables that you wont be using again outside of that if/else.