最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - JavaScript: TryCatch vs error function passed as a parameter - Stack Overflow

programmeradmin0浏览0评论

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: .html#domain_warning_don_t_ignore_errors

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/api/domain.html#domain_warning_don_t_ignore_errors

Share Improve this question edited Aug 27, 2014 at 12:12 Purple Dragon asked Aug 27, 2014 at 12:03 Purple DragonPurple Dragon 5,3586 gold badges35 silver badges37 bronze badges 1
  • Well, the main limitations of native try/catch is that it's not typed (you have to either catch everything or nothing and that it doesn't work with asynchronous functions (in Node you can work around that with domains, or even better - just use promises which are throw safe). If those two are not concerns prefer native syntax. – Benjamin Gruenbaum Commented Aug 27, 2014 at 12:06
Add a ment  | 

2 Answers 2

Reset to default 4

It's totally up to you. Exceptions have the advantage of providing a stack trace.

Note that if dangerous.function does its work asynchronously, then you'll need to use your second approach, since there isn't any exception to catch initially. But that doesn't mean you can't use an exception, just that if you want to use an exception, you have to pass the exception to the callback rather than throwing it. (Or don't use an exception, that's also totally up to you.)

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.

发布评论

评论列表(0)

  1. 暂无评论