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

Why used 'new' here?

I am confused with this line:

const statusCodeError = new Error(message);

Though I know basic of constructor functions, I didn't understand how 'new' came here. Why didn't we use the same syntax in other parts of the code?

2 Answers

As Christian Russo said, we're creating an instance of the Error constructor. The reason why the teacher used the new keyword, instead of using the passed error object in the catch block, is because we want to create a new error object with our own message.

In other words, the error object the teacher used in 'the same syntax in other parts of the code' is an error object created by Node, while our new error object is a creation of our own, with its own message and other information (like statusCode).

You would want to create your own error object when you want to relay a specific error message of your own with a specific error code. For example, in Node (or perhaps any other language), there is no built-in error object with the message 'There was an error getting the profile for ${username} (${response.statusCode})', you must create it yourself.

I am another student with the same doubt. Your answer is very clear. Thank you for your explanation!

We're creating an instance from the Error constructor, which will be bound to the variable 'statusCodeError'. I hope that's a little bit more helpful!