异步函数永远不会抛出? [英] Should async function never ever throw?

查看:137
本文介绍了异步函数永远不会抛出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个带有多个异步函数的库。
如果其中一个参数显然为错误,SYNCHRONOUS帮助函数会抛出错误:

  proto.makeParameters = function过滤器){
default:
throw(new Error(Field type unknown:+ fieldObject.type));
break;
}

在我的异步函数中,当我使用它时,我有:

  proto.someAsyncFunction = function(cb){

//运行查询
try {
var parameters = this.makeParameters(filters);
} catch(e){
return cb(e);
}
}

所以:




  • 异步函数是不是永远不会抛出的好习惯? (像我一样)


  • 现在,我遇到所有的错误。我会更多选择吗?可能会组成一个错误类型,只是检查一下?如果是这样,在两种情况下应该怎么办?



解决方案

在异步代码是正确的。参见Isaac Schlueter自己的这篇文章主题:


节点中的模式是同步方法throw,而异步方法传递
将错误作为回调的第一个参数。如果您的回调的第一个
参数为false(通常为空或未定义),则
全部与世界相当。


http://groups.google.com/forum/ #!msg / nodejs / W9UVJCKcJ7Q / rzseRbourCUJ


I wrote a library with a number of async functions. A SYNCHRONOUS helper function throws an error if one of the parameters is plain wrong:

proto.makeParameters= function( filters ){
  default:
    throw( new Error("Field type unknown: " + fieldObject.type ) );
  break;
}

In my async functions, when I use it, I have:

proto.someAsyncFunction = function( cb ){

  // Run the query
  try {
    var parameters = this.makeParameters( filters );
  } catch( e ){
   return cb( e );
  }
}

So:

  • Is it good practice that asyncfunctions should never ever throw? (Like I did)

  • Right now, I am catching ALL errors. Shall I e more choosy? Maybe make up an error type and just check for that? If so, what should I do in either case?

解决方案

Your assumptions on the async code are correct. See this post by Isaac Schlueter himself on the topic:

The pattern in node is that sync methods throw, and async methods pass the error as the first argument to the callback. If the first argument to your callback is falsey (usually null or undefined), then all is well with the world.

http://groups.google.com/forum/#!msg/nodejs/W9UVJCKcJ7Q/rzseRbourCUJ

这篇关于异步函数永远不会抛出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆