ErrorHandling 範例示範如何使用 介面,擴充對 Windows Communication Foundation (WCF) 服務IErrorHandler中錯誤處理和錯誤報告的控制權。 此範例是以 Getting Started 為基礎,並在該服務中添加了一些額外的程式代碼以處理錯誤。 用戶端會強制數個錯誤狀況。 服務會攔截錯誤,並將其記錄在檔案中。
備註
此範例的安裝程式和建置指示位於本主題結尾。
服務可以攔截錯誤、執行處理,以及影響使用 IErrorHandler 介面報告錯誤的方式。 介面有兩種方法可以實作: ProvideFault(Exception, MessageVersion, Message) 和 HandleError。 ProvideFault(Exception, MessageVersion, Message)方法可讓您新增、修改或隱藏回應例外狀況時產生的錯誤訊息。 HandleError方法允許在發生錯誤時進行錯誤處理,並控制是否可以執行其他錯誤處理。
在此範例中 CalculatorErrorHandler
,類型會實作 IErrorHandler 介面。 在
HandleError 方法,會將 CalculatorErrorHandler
錯誤的記錄寫入 c:\logs 中的 Error.txt 文本檔。 請注意,範例會記錄錯誤,而且不會隱藏錯誤,因此可將其回報給用戶端。
public class CalculatorErrorHandler : IErrorHandler
{
// Provide a fault. The Message fault parameter can be replaced, or set to
// null to suppress reporting a fault.
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
}
// HandleError. Log an error, then allow the error to be handled as usual.
// Return true if the error is considered as already handled
public bool HandleError(Exception error)
{
using (TextWriter tw = File.AppendText(@"c:\logs\error.txt"))
{
if (error != null)
{
tw.WriteLine("Exception: " + error.GetType().Name + " - " + error.Message);
}
tw.Close();
}
return true;
}
}
ErrorBehaviorAttribute
存在作為向服務註冊錯誤處理程序的機制。 此屬性接受單一類型參數。 該類型應該實作 IErrorHandler 介面,而且應該有公用的空建構函式。 屬性接著會具現化該錯誤處理程式類型的實例,並將它安裝到服務中。 其做法是實作 IServiceBehavior 介面,然後使用 ApplyDispatchBehavior 方法將錯誤處理程序的實例新增至服務。
// This attribute can be used to install a custom error handler for a service.
public class ErrorBehaviorAttribute : Attribute, IServiceBehavior
{
Type errorHandlerType;
public ErrorBehaviorAttribute(Type errorHandlerType)
{
this.errorHandlerType = errorHandlerType;
}
void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
{
}
void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters)
{
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
{
IErrorHandler errorHandler;
try
{
errorHandler = (IErrorHandler)Activator.CreateInstance(errorHandlerType);
}
catch (MissingMethodException e)
{
throw new ArgumentException("The errorHandlerType specified in the ErrorBehaviorAttribute constructor must have a public empty constructor.", e);
}
catch (InvalidCastException e)
{
throw new ArgumentException("The errorHandlerType specified in the ErrorBehaviorAttribute constructor must implement System.ServiceModel.Dispatcher.IErrorHandler.", e);
}
foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
{
ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;
channelDispatcher.ErrorHandlers.Add(errorHandler);
}
}
}
此範例會實作計算機服務。 客戶故意提供不合法的參數值,在服務中引發兩個錯誤。
CalculatorErrorHandler
使用 IErrorHandler 介面將錯誤記錄到本機檔案,然後將它們回報給用戶端。 用戶端會強制除以零和自變數超出範圍的條件。
try
{
Console.WriteLine("Forcing an error in Divide");
// Call the Divide service operation - trigger a divide by 0 error.
value1 = 22;
value2 = 0;
result = proxy.Divide(value1, value2);
Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);
}
catch (FaultException e)
{
Console.WriteLine("FaultException: " + e.GetType().Name + " - " + e.Message);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.GetType().Name + " - " + e.Message);
}
當您執行範例時,作業要求和回應會顯示在用戶端控制台視窗中。 您會看到除以零和參數超出範圍的情況被報告為錯誤。 在客戶端視窗中按 ENTER 鍵以關閉用戶端。
Add(15,3) = 18
Subtract(145,76) = 69
Multiply(9,81) = 729
Forcing an error in Divide
FaultException: FaultException - Invalid Argument: The second argument must not be zero.
Forcing an error in Factorial
FaultException: FaultException - Invalid Argument: The argument must be greater than zero.
Press <ENTER> to terminate client.
檔案 c:\logs\errors.txt 包含服務記錄錯誤的相關信息。 請注意,若要讓服務寫入目錄,您必須確定服務正在執行的進程(通常是 ASP.NET 或網路服務)具有寫入目錄的許可權。
Fault: Reason = Invalid Argument: The second argument must not be zero.
Fault: Reason = Invalid Argument: The argument must be greater than zero.
要設定、建置和執行範例,請執行以下步驟:
請確定您已針對 Windows Communication Foundation 範例 執行One-Time 安裝程式。
若要建置解決方案,請遵循 建置 Windows Communication Foundation 範例中的指示。
請確定您已建立 c:\logs directory for the error.txt 檔案。 或修改
CalculatorErrorHandler.HandleError
中使用的檔名。若要在單一或跨計算機組態中執行範例,請遵循執行 Windows Communication Foundation 範例 中的指示。