Search code examples
javascriptnode.jserror-handlingtry-catchconceptual

JavaScript: Try/Catch vs error function passed as a parameter


I am wondering which approach is better for error handling and debugging in JavaScript for nodeJS?

Having a pure try/catch block:

try
{
  dangerous.function();

}
catch(error);
{
  console.log(error);
}

or

Just using a function as a parameter, which will display if any errors occur

dangerous.function(function(error)
{
  console.log(error);
});

I am raising this question because I read that try/throw has a potential of logging too much stack trace data as written here: http://nodejs.org/api/domain.html#domain_warning_don_t_ignore_errors


Solution

  • They aimed to fulfill the same purpose, but they are to be used in different contexts:

    • try/catch will only work to intercept synchronous errors
    • callback will allow both synchronous and asynchronous errors transmission

    I strongly advice to read this article (even though it is first addressed for Node.js developers, it is valuable for every JavaScript developer) which fully covers the subject.