正确的方式Mongo DB连接的C#异常处理

use*_*979 3 c# exception-handling mongodb

我的mongoDB托管在Mongo Lab上,我使用C#作为检索数据的代码.

mongo查询中有10次抛出异常:

System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
Run Code Online (Sandbox Code Playgroud)

我让MongoLab调查该持续时间的日志报告,他们说没有任何东西从他们身边登录并建议我使用正确的mongo异常处理.

我的问题:我应该如何处理C#中的Mongo异常?

我应该如下做.在catch中再次查询一次或两次:

   /*Connection part

    ----
    ----
    */
    List X<XYZ> = new List<XYZ>;
    try{
    var Query = from o in collection.AsQueryable<XYZ>()
                             where ...
                             select o;

    List= Query.ToList();
    }
    catch(MongoException e){
var Query = from o in collection.AsQueryable<XYZ>()
                             where ...
                             select o;
    List= Query.ToList();
    }
Run Code Online (Sandbox Code Playgroud)

感谢您提前帮助.

Pet*_*uck 7

你永远不应该把你的程序逻辑的任何实质部分放在一个catch子句中.如果再次抛出异常会发生什么?换句话说,该catch子句中的所有内容都应该足够简单,以确保不会失败.

您可以做的是将整个块放入循环并设置重试计数器,如果它未能达到预定(或可配置)次数,则退出:

List<XYZ> list = null;
const int maxRetries = 3; // could also be a configuration parameter

int retries = maxRetries;
while ((retries > 0) && (list == null)) {
  try{
    var Query = from o in collection.AsQueryable<XYZ>()
                         where ...
                         select o;

    list = Query.ToList();
  }
  catch {
    retries--;

    if (retries < 1) {
      throw;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这将最多尝试您的查询3次.如果查询成功并成功转换为List,则循环退出.如果抛出异常,则重试计数器递减.如果达到最大重试次数,则会重新抛出异常.