2015-10-16 199 views
2

我有一個WCF服務,我已經實現了一個自定義服務錯誤。我正在拋出一個基於特定條件的錯誤,所以在if語句中,我會拋出下面的錯誤。如何獲取異常詳細信息

throw new FaultException<CustomServiceFault>(
    new CustomServiceFault 
    { 
     ErrorMessage = string.Format(
      "Error in response, code:{0} message:{1}", 
      response.Error.Code, 
      response.Error.Message), 
     Source = "ConnectToOpenLdap Method", 
     StackTrace = string.Format(
      "Error in response, code:{0} message:{1}", 
      response.Error.Code, 
      response.Error.Message)          
    }, 
    new FaultReason(
     string.Format(CultureInfo.InvariantCulture, "{0}", "Service fault exception"))); 

在抓我重新拋出異常這樣的:

catch (Exception exception) 
{ 
    var customServiceFault = GetCustomException(exception); 
    throw new FaultException<CustomServiceFault>(
     customServiceFault, 
     new FaultReason(customServiceFault.ErrorMessage), 
     new FaultCode("Sender"));    
} 

的GetCustomException()方法簡單異常轉換成我的自定義異常對象。

問題是傳遞給GetCustomException()的異常沒有InnerException屬性中的細節。的我所看到的截圖:

enter image description here

我如何提取或獲取定製的ErrorMessage,來源等我的,如果條件拋出異常時設定?正如你在截圖中看到的,擴展的「exception」顯示對象類型(我相信),而在「Detail」內部顯示ErrorMessage,InnerExceptionMesage,Source和StackTrace。這就是我所追求的。如何在GetCustomException()方法中提取這些值?

這是GetCustomException()方法:

private static CustomServiceFault GetCustomException(Exception exception) 
{      
    var customServiceFault = new CustomServiceFault 
    { 
     ErrorMessage = exception.Message, 
     Source = exception.Source, 
     StackTrace = exception.StackTrace, 
     Target = exception.TargetSite.ToString() 
    };  

    return customServiceFault; 
} 

CustomServiceFault類:

[DataContract] 
public class CustomServiceFault 
{ 
    [DataMember] 
    public string ErrorMessage { get; set; } 
    [DataMember] 
    public string StackTrace { get; set; } 
    [DataMember] 
    public string Target { get; set; } 
    [DataMember] 
    public string Source { get; set; } 
    [DataMember] 
    public string InnerExceptionMessage { get; set; } 
} 
+0

請問您可以添加您的CustomServiceFault類嗎? – Lorek

+1

而不是'Exception',趕上'FaultException '。然後,您可以更改'GetCustomException()'方法的類型。然後,你可以訪問'Details'屬性。你也可以通過類型轉換來實現這一點。但是當你打算處理這些類型時,最好捕獲特定的異常類型。 – Lorek

+0

我加了CustomServiceFault類 – obautista

回答

4

你沒有得到InnerExceptionMessage因爲你還沒有設置任何地方。

private static CustomServiceFault GetCustomException(Exception exception) 
{      
    var customServiceFault = new CustomServiceFault 
    { 
     ErrorMessage = exception.Message, 
     Source = exception.Source, 
     StackTrace = exception.StackTrace, 
     Target = exception.TargetSite.ToString(), 

     // You should fill this property with details here. 
     InnerExceptionMessage = exception.InnerException.Message; 
    };  

    return customServiceFault; 
}