来自Catch块的重复调用(Recusive calls from a Catch block)

我正在编写一种方法,其中上传文档的尝试包含在Try / Catch块中。

如果尝试失败,我正在递增重试计数器并递归调用相同的方法。

在那些“Catch”块被击中的情况下,我不清楚执行路径。 初始测试表明,在第一次递归调用执行后执行'return null'语句。 也许'return null'语句需要在Catch块内,但在重试<3循环之外?

public RssUploadDocOutput UploadInvoice(string filename, int retries) { var returnsOutput = new RssUploadDocOutput(); GoogleSheetsCommand sscmd = new GoogleSheetsCommand("UploadDocument", ConnSheets); sscmd.CommandType = System.Data.CommandType.StoredProcedure; sscmd.Parameters.Add(new GoogleSheetsParameter("LocalFile", filename)); //int retries = 0; removed try { GoogleSheetsDataReader rdr = sscmd.ExecuteReader(); rdr.Read(); returnsOutput.ID = rdr[0].ToString(); [...] returnsOutput.Weblink = rdr[6].ToString(); return returnsOutput; } catch (Exception ex) { //retries++; Logger.Instance.LogException(ex); if (retries < 3) { Thread.Sleep(1000 * retries); UploadInvoice(filename, retries+1); } } return null; }

I'm coding a method where an attempt to upload a document is wrapped within a Try/Catch block.

If the attempt fails, I'm incrementing the Retry counter and recursively calling the same method.

I'm not clear on the execution path in those cases where the 'Catch' block is hit. Initial tests show that the 'return null' statement is executed after that first recursive call executes. Perhaps the 'return null' statement needs to be within the Catch block but outside the retries<3 loop?

public RssUploadDocOutput UploadInvoice(string filename, int retries) { var returnsOutput = new RssUploadDocOutput(); GoogleSheetsCommand sscmd = new GoogleSheetsCommand("UploadDocument", ConnSheets); sscmd.CommandType = System.Data.CommandType.StoredProcedure; sscmd.Parameters.Add(new GoogleSheetsParameter("LocalFile", filename)); //int retries = 0; removed try { GoogleSheetsDataReader rdr = sscmd.ExecuteReader(); rdr.Read(); returnsOutput.ID = rdr[0].ToString(); [...] returnsOutput.Weblink = rdr[6].ToString(); return returnsOutput; } catch (Exception ex) { //retries++; Logger.Instance.LogException(ex); if (retries < 3) { Thread.Sleep(1000 * retries); UploadInvoice(filename, retries+1); } } return null; }

最满意答案

需要两个变化:

在函数外部声明变量重试

返回UploadInvoice方法返回的值(在catch块中)

if (retries < 3) { Thread.Sleep(1000 * retries); return UploadInvoice(filename); }

Needs two changes:

Declare the variable retries outside of the function

Return the value returned by the UploadInvoice method (in the catch block)

if (retries < 3) { Thread.Sleep(1000 * retries); return UploadInvoice(filename); }

更多推荐