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 trialada ada
Front End Web Development Techdegree Student 192 PointsWhen to use try catch and when to use request.on(error)?
When to use try catch and when to use request.on(error)?
Also what is the difference between them?
2 Answers
Dylan Macnab
24,861 PointsTo the best of my understanding...
Try/catch is used to handle an error event when using a node API like https to make sure the arguments are all valid. If there's an issue with one of the arguments (e.g. url endpoint typo) then it will immediately throw an error to the catch(error) block.
request.on('error') is used to return an error specifically when you're listening for an error event to happen during a request. This is useful in the situation where the .get call is valid but for whatever reason the responseCode returns an error. This will trigger the on error event and log your error to the console.
polentz
Full Stack JavaScript Techdegree Student 11,755 PointsI will try to explain it in the best way I can :
request.on('error') catches errors happening during the ASYNCHRONOUS operation, in this case the request to the treehouse's API. Conversely, try catch block are used to catch/handle errors for SYNCHRONOUS operations. When the http:// is removed from the url, an Asynchronous call has not started yet, the execution of the code is still Synchronous. You should not use try/catch blocks to handles errors in Asynchronous operation, but only for the part of the code that is Synchronous.
If you try to use try/catch block to handle errors in asynchronous operations, the catch part of the block will not execute in case an error happens during the asynchronous operation (the API request for example) as the program does not stop its execution waiting for the API server to respond, but it continues to read and execute the rest of the program. This means that the control of the program, is simple terms, proceeded ahead and is no longer aware of a catch block. therefore when an error occurs you will probably see that other statements were executed and the error in the async call interrupts the program without being handled in the catch block.
Hope it helps, although it is difficult to explain without example