我有一个try,catch和finally块的函数.如果捕获到异常,那么我会捕获该异常的某些参数,例如其错误代码,错误详细消息和消息,并将其打印在excel文件中.我发布以下相关代码:
public void UpdateGroup(String strSiteID,String strGroup,int row) { try { Console.WriteLine("UpdateGroup"); Excel1.MWMClient.MWMServiceProxy.Group group = new Excel1.MWMClient.MWMServiceProxy.Group(); group.name = "plumber"; group.description = "he is a plumber"; Console.WriteLine(groupClient.UpdateGroup(strSiteID,group)); ExcelRecorder(0,null,row); } catch (System.ServiceModel.FaultException<DefaultFaultContract> ex) { ExcelRecorder(ex.Detail.ErrorCode,ex.Detail.Message,ex.Message,row); } finally { System.GC.Collect(); } } public void ExcelRecorder(int error,string detailmessage,string message,int row) { Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"D:/WebServiceTestCases_Output.xlsx"); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; if (!string.IsNullOrEmpty(message)) { ((Range)xlWorksheet.Cells[row,"M"]).Value2 = "FAIL"; ((Range)xlWorksheet.Cells[row,"N"]).Value2 = error; ((Range)xlWorksheet.Cells[row,"O"]).Value2 = detailmessage; ((Range)xlWorksheet.Cells[row,"P"]).Value2 = message; } else { ((Range)xlWorksheet.Cells[row,"M"]).Value2 = "PASS"; ((Range)xlWorksheet.Cells[row,"N"]).Value2 = ""; ((Range)xlWorksheet.Cells[row,"O"]).Value2 = ""; ((Range)xlWorksheet.Cells[row,"P"]).Value2 = ""; } xlWorkbook.Save(); xlWorkbook.Close(0,0); xlApp.Quit(); }
问题是,早些时候我有一段代码就像
catch(Exception ex) { ExcelRecorder(ex.Message); }
那时,所有例外都被抓住了.但是,后来需求发生了变化,因为我还需要捕获错误详细信息代码和错误详细信息.所以,我用catch(System.ServiceModel.FaultException ex)改变了我的catch块,因为它允许我获取那些参数.但是现在,某些例外情况并没有被捕获.如何更改我的catch块以便能够捕获所有异常?
解决方法
基本上有两种方式:
1:两个捕获块(最具体的第一个):
catch (System.ServiceModel.FaultException<DefaultFaultContract> ex) { ExcelRecorder(ex.Detail.ErrorCode,row); } catch (Exception ex) { // TODO: simpler error handler }
2:一个带有测试的catch块:
catch (Exception ex) { var fault = ex as System.ServiceModel.FaultException<DefaultFaultContract>; if(fault != null) { ExcelRecorder(fault.Detail.ErrorCode,fault.Detail.Message,fault.Message,row); } // TODO: common error handling steps }
要么可以工作.第一个可能更干净,但是如果你想在捕获物内部做很多常见的事情,第二个可能有优势.