关于重试容错封装的一些技巧

Author: Zero, Created: 2015-07-20 22:01:59, Updated: 2015-07-20 22:06:32

交易所网络原因导致的错误会致使比如exchange.GetAccount这样的函数调用失败, 这时候就需要重试了, 但每个函数都重试一次显的代码过于烦锁, 可以这样解决:

这个函数放到开头

function EnsureCall(method) {
    var r;
    while (!(r = method.apply(this, Array.prototype.slice.call(arguments).slice(1)))) {
        Sleep(300);
    }
    return r;
}```
然后比如获取账户信息可以这样
```var account = EnsureCall(exchange.GetAccount);```
获取深度可以这样
```var depth = EnsureCall(exchange.GetDepth);```
要传入参数可以这样
```var records = EnsureCall(exchange.GetRecords, PERIOD_M5);```
这样以来,不管交易所网络如何不稳定, EnsureCall会重试得到的都是有效的数据, 不用每个函数都为了容错封装一次了.

当然你也可以把EnsureCall改名为EC或者Call之类好记又短的名子, 这样更方便.

More

simple-chun 请问这个有PY版本吗?

solorez function EnsureCall(method) { var r; while (!(r = method.apply(this, Array.prototype.slice.call(arguments).slice(1)))) { Sleep(300); } return r; } function main() { InitAccount = EnsureCall(exchange.GetAccount()); Log(InitAccount); } 像上面这种调用,就会出现错误。

solorez 我觉得你再做api的时候,把这个容错考虑进去最好。

solorez 大神测试过了吗?为什么我用的时候,出现这个错误: https://dn-filebox.qbox.me/bdfed9d5bfd320ceaa06732c84ef0dd1662dc3f8.png

Zero ```EnsureCall(exchange.GetAccount)``` GetAccount后面不用加()