简体   繁体   中英

correct way C# exception handling for Mongo DB connections

my mongoDB is hosted on Mongo Lab and i am using C# as the code to retrieve the data.

1 out of 10 times the mongo query throws an exception:

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)

I asked MongoLab to investigate the log report for that time duration and they said there was nothing logged in from their side and advised me to use correct mongo exception handling.

My Question: How should i handle Mongo exceptions in C#?

Should i do it as follows. Query again inside catch once or twice:

   /*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();
    }

Thanks for helping in advance.

You should never put any substantial part of your program logic inside a catch clause. What happens if the exception is thrown a second time? In other words, everything in the catch clause should be simple enough that it is guaranteed not to fail.

What you could do is put your entire block into a loop and set a retry counter to exit if it fails a pre-determined (or configurable) number of times:

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;
    }
  }
}

This will try your query up to 3 times. If the query succeeds and converts to List successfully, then the loop exits. If an exception is thrown, the retry counter is decremented. If the maximum number of retries is reached, it will rethrow the exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM