JavaScript Node.js Basics 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
12,678 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.