2016-02-29 55 views
2

我不太清楚如何提出這個問題。我真的很希望我能解釋我的問題是什麼。c#返回組合異常

我有多個自定義異常分佈在我的windows-service中,我想回饋給啓動過程步驟的主進程。

例如,我有靜態類PropertyMapper,它使用反射來讀取email-headers並將它們反映到特定的屬性。現在,如果出現異常,我想添加其他信息。像headerattribute實際上導致了異常,但我不想失去「實際」異常。

目前,它看起來像這樣:

try 
{ 
    PropertyInfo pInfo = prop.Property; 
    Type t = Nullable.GetUnderlyingType(pInfo.PropertyType) ?? pInfo.PropertyType; 
    object safeValue = (headerAttribute.Value == null) ? null : Convert.ChangeType(headerAttribute.Value, t); 
    pInfo.SetValue(mailDataObj, safeValue, null); 
} 
catch (Exception e) 
{ 
    throw new PropertyMappingFailedException(headerAttribute.Field, headerParam); 
} 

我拋出異常攜帶它返回到主過程,使我只需要貫徹「創建logEntry邏輯」一次。 '

try 
{ 
    mailDataObj = PropertyMapper.MapProperties(mailItem); 
    mailDataObj.MailItem = mailItem; 
    controller = new DAKMailController(mailDataObj); 

    controller.SetBasicData(procFile); 
    controller.HandlePostProcessing(); 
} 
catch (Exception e) 
{ 
    controller.CreateLogEntry(e); 
    moveFileToError(file); 
} 

現在當然,我毫無遺漏原來丟失,因爲我不把它添加到我的自定義異常,但我怎麼做,反正例外呢?另外,我的思維方式是否正確,還是必須以其他方式處理異常?

我已經google了一下,但沒能找到有用的東西。我會很感激一些幫助。 :)

P.S.我提取了CreateLogEntry方法中的所有InnerExcectivity,並將它們放入單個字符串-var中。

回答

3

裹原始異常在該領域的InnerException像這樣(在你的第一個代碼示例的捕撈):

throw new PropertyMappingFailedException(headerAttribute.Field, headerParam) 
{ InnerException = e }; 
+0

但是,InnerException是隻讀的? – brocrow

+0

啊,哦。是否有可能將內部異常作爲參數發送給構造函數(比您使用的另一個超載)? –

+0

'拋出新的CustomException(「我的消息」,前)'這是你正在談論的stacktrace的語法是字符串 –

1

通常你不會例外添加到對方,但你總結堆棧跟蹤時:

throw ex,然後stracktrace不見了,(重置),但當您使用:

throw然後它不。

此外,你總是捕捉所有類型的例外,但你沒有添加stacktrace。最佳實踐看上去更像是:

class Foo 
{ 
    DoSomething(int param) 
    { 
     try 
     { 
      if (/*Something Bad*/) 
      { 
       //violates business logic etc... 
       throw new FooException("Reason..."); 
      } 
      //... 
      //something that might throw an exception 
     } 
     catch (FooException ex) 
     { 
      throw; 
     } 
     catch (Exception ex) 
     { 
      throw new FooException("Inner Exception", ex); 
     } 
    } 
} 
在總結

,所以你需要用Inner Exception

樂於助人的鏈接玩:

Throwing Custom Exception Best Practices

Is there a difference between 「throw」 and 「throw ex」?

Best Practices for Exceptions

Throw exception but persist stack trace

+0

在大多數情況下,我只是這麼做的,但是反射會拋出如此多的不同異常,以至於如果嘗試用if來捕捉它們都是沒有意義的,因爲有許多不同的數據類型必須從字符串轉換爲日期,整數,smallint,...更不用說在x個不同的表達式中會出現x個不同的異常。非常感謝所有的信息。不過,我想現在我會用骯髒的解決方法。 – brocrow