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 the Error Event in Node

Peter Retvari
seal-mask
.a{fill-rule:evenodd;}techdegree
Peter Retvari
Full Stack JavaScript Techdegree Student 8,392 Points

request.on vs. try--catch

Dears,

I would like to know is there any other way to make the error handling more user-friendly without the try {}? Maybe it's a stupid question, but can we handle the second type of error (missing protocol language) with a similar simple code, like we did in the first error (wrong URL)?

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

Because this kind of error (try) handling makes my code almost unreadable for me.

1 Answer

Tiago Fernandes
Tiago Fernandes
3,647 Points

Hi Peter

I found another solution that could help you.

const https = require('https');

https.get('https://teamtreehouse.com/tiagofernandes98.json', (res) => {

//if-statement 
 if(res.statusCode !== 200){              //if not 200 then console.log
  console.log('Ooops! Something went wrong!')
}

regards Tiago

polentz
seal-mask
.a{fill-rule:evenodd;}techdegree
polentz
Full Stack JavaScript Techdegree Student 11,755 Points

Hi Tiago, this solution does not seem to work entirely. As far as I learned, we use try/catch for synchronous code, the error handling in the example above is implemented in a way that it catches an error if something went wrong during the API call, which is asynchronous. A malformed URL, like one missing the http/s protocol in the string, would throw an error before the async API call is even initiated, therefore the error would remain unhandled. The solution with the try/catch block would instead catch it. As rule of thumb, as far as my knowledge goes, use the try/catch in synchronous code, while use the callback with the error object to catch error happening during async calls.