我可以轻松判断`Function.apply`是否因参数计数错误而失败?

时间:2014-09-21 16:30:53

标签: dart

我在Web服务器中有一些代码将路由映射到处理程序,如下所示:

final Map<String, Handler> handlers = {
  r'/index.html': StaticFileHandler('./web'),
  r'/test/(\d+)/(\d+)': MyTestHandler
};

MyTestHandler(HttpRequest request, int number1, int number2) {
  request.response.headers.contentType = new ContentType('text', 'html');
  request.response.write('<h1>$number1 ($number2)</h1>');
  request.response.close();
}

为了支持正则表达式作为参数,我必须在提取参数后使用Function.apply;这意味着没有开发人员检查或与处理程序的路由。如果你得到错误数量的正则表达式组与处理程序参数;它像这样爆炸:

Unhandled exception:
Uncaught Error: Closure call with mismatched arguments: function 'call'

NoSuchMethodError: incorrect number of arguments passed to method named 'call'
Receiver: Closure: (HttpRequest, int) => dynamic from Function 'MyTestHandler': static.
Tried calling: call(Instance of '_HttpRequest', "2", "3")
Found: call(request, number)
Stack Trace:

这对开发人员来说并不是很明显出了什么问题;所以我宁愿抛出一个更容易解释问题的自定义错误。

我是否有一种简单的方法可以检测到这种失败(例如,获取函数所期望的参数数量):

  1. 不使用像Mirrors这样的东西
  2. 不涉及捕捉所有例外情况;因为这会阻碍调试,并且可能由处理代码的用户在处理程序内调用同样的错误;而且我不想干扰该错误消息

1 个答案:

答案 0 :(得分:4)

你可以做的是创建一些typedef(每个可能的签名一个),然后使用is检查它们,或者你可以将参数作为数组传递。

此答案包含代码示例https://stackoverflow.com/a/22653604/217408

(刚复制)

typedef NullaryFunction();

main () {
  var f = null;
  print(f is NullaryFunction);  // false
  f = () {};
  print(f is NullaryFunction);  // true
  f = (x) {};
  print(f is NullaryFunction);  // false
}