2011-11-02 211 views
1

我發現了一堆非常接近我需要的問題。但是我擔心我錯過了一些重要的信息。WCF Rest .NET 4.0未處理的異常

如何使用WCF Rest與.NET 4.0捕獲所有未處理的異常?

爲了安全起見,我不希望未處理的異常進入客戶端。我想記錄所有異常,並且發現500個內部服務器錯誤。

迄今爲止,我的最佳研究告訴我需要實現IErrorHandler併爲已知的異常拋出WebFaultExceptions。我遇到的一個問題是,我的所有業務邏輯都與WCF服務位於一個單獨的項目中,並且從基礎類庫中拋出Web異常是沒有意義的,因爲類庫可能會被另一個進程可能不是WCF Rest服務。有沒有一種很好的方法來映射異常?

回答

1

是的,你可以實現IErrorHandler並用它來映射異常。您不需要從業務邏輯中拋出WebFaultException,只需拋出自定義異常。

例如,您可以將YourCustomException映射到一些簡單的json字符串。你可以放置一些對象而不是字符串。樣品IErrorHandler.ProvideFault實現:

public void ProvideFault(Exception error, MessageVersion version, ref Message fault) 
{   
     if (error is YourCustomException) 
     { 
      fault = Message.CreateMessage(version, string.Empty, String.Format("Error: {0}.", error.Message), new DataContractJsonSerializer(typeof(string))); 
      fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json)); 

      webOperationContextWrapper.SetOutgoingResponseStatusCode(HttpStatusCode.InternalServerError); 
     } 
} 

所以當YourCustomException是業務邏輯拋出,將被處理程序獲取,並轉換成正確的故障。

另請參閱:CodeProject article