我在 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:
对于开发人员来说,这并不是完全显而易见的问题所在;所以我宁愿抛出一个自定义错误来更容易地解释问题。
有没有一种简单的方法可以检测到此故障(例如,获取函数期望的参数数量):
- 不使用镜子等笨重的东西
- 不涉及捕获所有异常;因为这会妨碍调试,并且用户处理代码可能会从处理程序内调用相同的错误;我不想干扰该错误消息
最佳答案
您可以做的是创建一些 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
}
关于dart - 我可以轻松判断 `Function.apply` 是否会因参数计数不正确而失败吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25961355/