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
harishn
3,103 PointsWhy do we need separate try/catch block while there is an "error" event that could be delegated using .on() method?
Why do we need separate try/catch block while there is an "error" event that could be delegated using .on() method?
For ex: Referring to tutorial "Handling Parsing and Status Code Errors" under Part 1 of Intro to Node.js, we have code like below:
function printError(error) { console.log(error.message); }
response.on('end', function() { try { } catch (error) { printError(error); } });
response.on("error", printError);
2 Answers
Adam Bowers
11,812 PointsI may be wrong but on .end is the the completion of the response object. Try/Catch is not Asynchronous, so would suffice for the res.end method to catch any errors.
Whereas on response.on("error", function(error){...}); would be something wrong with the http servers response and would need to be handled asynchronously with a callback function.
Ryan Schurton
13,815 PointsHello Harish,
The .on is exclusive to JQuery. If you where working on a project that didn't include JQuery. You would need to use a try/catch to handle your errors.
.on('error') needs to be chained to an element to be tested for errors. So it may be good to check if a certain image loaded. However not effected when you want to check if a certain Variable had a particular value, or if a block of code suddenly failed.
Try/catch offers a variety of properties and methods that can be accessed through the error object. To check the status of your errors.
There is so much information about try/catch I suggest a good old fashion google search.
Good luck.