我用:
1) AppDomain.CurrentDomain.UnhandledException 事件
2) TaskScheduler.UnobservedTaskException 事件
3) 错误处理程序:
public class ErrorHandler : IErrorHandler
{
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
var faultException = new FaultException<string>("Server error: " + error.Format());
var messageFault = faultException.CreateMessageFault();
fault = Message.CreateMessage(version, messageFault, null);
}
public bool HandleError(Exception error)
{
return false;
//return true; //if handled
}
}
[AttributeUsage(AttributeTargets.Class)]
public class ErrorHandlerBehavior : Attribute, IEndpointBehavior, IServiceBehavior
{
public void Validate(ServiceEndpoint endpoint)
{
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(new ErrorHandler());
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
{
channelDispatcher.ErrorHandlers.Add(new ErrorHandler());
}
}
}
这可以应用于整个服务实现。班级:
[ErrorHandlerBehavior]
public class SubscriberInfoTaskService : {}
或到端点:
var endpoint = Host.Description.Endpoints.FirstOrDefault();
//foreach (ChannelDispatcher channelDispatcher in Host.ChannelDispatchers) //ChannelDispatcherBase
//{
// channelDispatcher.ErrorHandlers.Add(new ErrorHandler());
//}
endpoint.Behaviors.Add(new ErrorHandlerBehavior());
这里关于使用配置: http: //www.steverb.com/post/2008/11/24/Useful-WCF-Behaviors-IErrorHandler.aspx