IErrorHandler 接口
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
允许实施者对返回给调用方的错误消息进行控制,还可以选择执行自定义错误处理,例如日志记录。
public interface class IErrorHandler
public interface IErrorHandler
type IErrorHandler = interface
Public Interface IErrorHandler
示例
下面的代码示例演示了服务方法引发托管异常时,实现 IErrorHandler(仅返回类型为 FaultException<TDetail> 的 GreetingFault
)的服务。
#region IErrorHandler Members
public bool HandleError(Exception error)
{
Console.WriteLine("HandleError called.");
// Returning true indicates you performed your behavior.
return true;
}
// This is a trivial implementation that converts Exception to FaultException<GreetingFault>.
public void ProvideFault(
Exception error,
MessageVersion ver,
ref Message msg
)
{
Console.WriteLine("ProvideFault called. Converting Exception to GreetingFault....");
FaultException<GreetingFault> fe
= new FaultException<GreetingFault>(new GreetingFault(error.Message));
MessageFault fault = fe.CreateMessageFault();
msg = Message.CreateMessage(
ver,
fault,
"http://microsoft.wcf.documentation/ISampleService/SampleMethodGreetingFaultFault"
);
}
#endregion
#Region "IErrorHandler Members"
Public Function HandleError(ByVal [error] As Exception) As Boolean Implements IErrorHandler.HandleError
Console.WriteLine("HandleError called.")
' Returning true indicates you performed your behavior.
Return True
End Function
' This is a trivial implementation that converts Exception to FaultException<GreetingFault>.
Public Sub ProvideFault(ByVal [error] As Exception, ByVal ver As MessageVersion, ByRef msg As Message) Implements IErrorHandler.ProvideFault
Console.WriteLine("ProvideFault called. Converting Exception to GreetingFault....")
Dim fe As New FaultException(Of GreetingFault)(New GreetingFault([error].Message))
Dim fault As MessageFault = fe.CreateMessageFault()
msg = Message.CreateMessage(ver, fault, "http://microsoft.wcf.documentation/ISampleService/SampleMethodGreetingFaultFault")
End Sub
#End Region
下面的代码示例演示了如何使用服务行为将 IErrorHandler 实现添加到 ErrorHandlers 属性。
// This behavior modifies no binding parameters.
#region IServiceBehavior Members
public void AddBindingParameters(
ServiceDescription description,
ServiceHostBase serviceHostBase,
System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints,
System.ServiceModel.Channels.BindingParameterCollection parameters
)
{
return;
}
// This behavior is an IErrorHandler implementation and
// must be applied to each ChannelDispatcher.
public void ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
{
Console.WriteLine("The EnforceGreetingFaultBehavior has been applied.");
foreach(ChannelDispatcher chanDisp in serviceHostBase.ChannelDispatchers)
{
chanDisp.ErrorHandlers.Add(this);
}
}
// This behavior requires that the contract have a SOAP fault with a detail type of GreetingFault.
public void Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
{
Console.WriteLine("Validate is called.");
foreach (ServiceEndpoint se in description.Endpoints)
{
// Must not examine any metadata endpoint.
if (se.Contract.Name.Equals("IMetadataExchange")
&& se.Contract.Namespace.Equals("http://schemas.microsoft.com/2006/04/mex"))
continue;
foreach (OperationDescription opDesc in se.Contract.Operations)
{
if (opDesc.Faults.Count == 0)
throw new InvalidOperationException(String.Format(
"EnforceGreetingFaultBehavior requires a "
+ "FaultContractAttribute(typeof(GreetingFault)) in each operation contract. "
+ "The \"{0}\" operation contains no FaultContractAttribute.",
opDesc.Name)
);
bool gfExists = false;
foreach (FaultDescription fault in opDesc.Faults)
{
if (fault.DetailType.Equals(typeof(GreetingFault)))
{
gfExists = true;
continue;
}
}
if (gfExists == false)
{
throw new InvalidOperationException(
"EnforceGreetingFaultBehavior requires a FaultContractAttribute(typeof(GreetingFault)) in an operation contract."
);
}
}
}
}
#endregion
' This behavior modifies no binding parameters.
#Region "IServiceBehavior Members"
Public Sub AddBindingParameters(ByVal description As ServiceDescription, ByVal serviceHostBase As ServiceHostBase, ByVal endpoints As System.Collections.ObjectModel.Collection(Of ServiceEndpoint), ByVal parameters As System.ServiceModel.Channels.BindingParameterCollection) Implements IServiceBehavior.AddBindingParameters
Return
End Sub
' This behavior is an IErrorHandler implementation and
' must be applied to each ChannelDispatcher.
Public Sub ApplyDispatchBehavior(ByVal description As ServiceDescription, ByVal serviceHostBase As ServiceHostBase) Implements IServiceBehavior.ApplyDispatchBehavior
Console.WriteLine("The EnforceGreetingFaultBehavior has been applied.")
For Each chanDisp As ChannelDispatcher In serviceHostBase.ChannelDispatchers
chanDisp.ErrorHandlers.Add(Me)
Next chanDisp
End Sub
' This behavior requires that the contract have a SOAP fault with a detail type of GreetingFault.
Public Sub Validate(ByVal description As ServiceDescription, ByVal serviceHostBase As ServiceHostBase) Implements IServiceBehavior.Validate
Console.WriteLine("Validate is called.")
For Each se As ServiceEndpoint In description.Endpoints
' Must not examine any metadata endpoint.
If se.Contract.Name.Equals("IMetadataExchange") AndAlso se.Contract.Namespace.Equals("http://schemas.microsoft.com/2006/04/mex") Then
Continue For
End If
For Each opDesc As OperationDescription In se.Contract.Operations
If opDesc.Faults.Count = 0 Then
Throw New InvalidOperationException(String.Format("EnforceGreetingFaultBehavior requires a " & "FaultContractAttribute(typeof(GreetingFault)) in each operation contract. " & "The ""{0}"" operation contains no FaultContractAttribute.", opDesc.Name))
End If
Dim gfExists As Boolean = False
For Each fault As FaultDescription In opDesc.Faults
If fault.DetailType.Equals(GetType(GreetingFault)) Then
gfExists = True
Continue For
End If
Next fault
If gfExists = False Then
Throw New InvalidOperationException("EnforceGreetingFaultBehavior requires a FaultContractAttribute(typeof(GreetingFault)) in an operation contract.")
End If
Next opDesc
Next se
End Sub
#End Region
下面的代码示例演示了如何通过使用应用程序配置文件来配置服务,从而加载服务行为。 有关如何在配置文件中公开服务行为的详细信息,请参见 IServiceBehavior。
<configuration>
<system.serviceModel>
<services>
<service
name="Microsoft.WCF.Documentation.SampleService"
behaviorConfiguration="metaAndErrors">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/SampleService"/>
</baseAddresses>
</host>
<endpoint
address=""
binding="wsHttpBinding"
contract="Microsoft.WCF.Documentation.ISampleService"
/>
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"
/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="metaAndErrors">
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceMetadata httpGetEnabled="true"/>
<enforceGreetingFaults />
</behavior>
</serviceBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add
name="enforceGreetingFaults"
type="Microsoft.WCF.Documentation.EnforceGreetingFaultBehavior, HostApplication, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
/>
</behaviorExtensions>
</extensions>
</system.serviceModel>
</configuration>
注解
若要在引发异常时显式控制应用程序的行为,请实现 IErrorHandler 接口并将其添加到 ChannelDispatcher的 ErrorHandlers 属性。 IErrorHandler 使你能够显式控制生成的 SOAP 错误,决定是否将其发送回客户端,并执行关联的任务,例如日志记录。 错误处理程序将按照它们向 ErrorHandlers 属性中的添加顺序进行调用。
实现 ProvideFault 方法可控制返回到客户端的错误消息。
实现 HandleError 方法可确保执行错误相关行为,包括错误日志记录、确保快速报告故障、关闭应用程序等。
注意
由于 HandleError 方法可以从许多不同的位置进行调用,所以不能确保该方法调用的线程。 不要依赖操作线程上调用的 HandleError 方法。
发送响应消息前,首先调用所有 ProvideFault 实现。 如果 ProvideFault 为非 fault
,则在调用了所有 null
实现且返回后,将根据操作协定将响应消息发送回客户端。 如果调用所有实现后,fault
为 null
,则响应消息将由 ServiceBehaviorAttribute.IncludeExceptionDetailInFaults 属性值控制。
注意
调用所有 ProvideFault 实现,并将响应消息传递到通道后,可能会发生异常。 例如,如果 (发生通道异常,则会通知) 对象序列化消息 IErrorHandler 时遇到困难。 在这种情况下,仍应确保开发环境捕获并显示此类异常,或使用跟踪来发现问题。 有关跟踪的详细信息,请参阅 使用跟踪对应用程序进行故障排除。
发送响应消息后,将以相同顺序调用所有 HandleError 实现。
通常,会将 IErrorHandler 实现添加到服务的 ErrorHandlers 属性;如果为双工通信,则还要添加到客户端的上述属性中。
您可通过实现行为(IErrorHandler、System.ServiceModel.Description.IServiceBehavior、System.ServiceModel.Description.IEndpointBehavior 或 System.ServiceModel.Description.IContractBehavior 对象)将 System.ServiceModel.Description.IOperationBehavior 添加到运行时,然后从配置文件、以编程方式使用所添加的行为,或利用自定义属性来附加您的 IErrorHandler。
有关使用行为修改运行时的详细信息,请参阅 使用行为配置和扩展运行时。
方法
HandleError(Exception) |
启用错误相关处理并返回一个值,该值指示调度程序在某些情况下是否中止会话和实例上下文。 |
ProvideFault(Exception, MessageVersion, Message) |
启用创建从服务方法过程中的异常返回的自定义 FaultException<TDetail>。 |