我有一个 WCF REST 服务,该服务在客户端上由经典使用:
WebResponse response = request.GetResponse();
我想拦截服务中出现的任何错误并将它们传递给客户端。默认情况下,当服务中发生异常时,会抛出错误异常并且通道出现故障,因此在客户端上我会收到错误请求。我希望能够向客户端返回 stackstrace 并覆盖行为而不是使通道出错。为此,我实现了 IErrorHandler
public class ErrorHandler : IErrorHandler
{
public bool HandleError(Exception error)
{
return true;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
fault = Message.CreateMessage(version, string.Empty, String.Format("An unknown error has occurred. The error identifier "), new DataContractJsonSerializer(typeof(string)));
fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
fault.Properties.Add(HttpResponseMessageProperty.Name, HttpStatusCode.Accepted);
}
}
问题是即使我在服务上注册它,我也可以调试错误处理程序,但通道仍然有故障,所以我仍然在客户端收到错误的请求。我为客户使用以下工厂:
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
var host = base.CreateServiceHost(serviceType, baseAddresses);
ServiceEndpoint ep = host.AddServiceEndpoint(serviceType, new WebHttpBinding(), "");
host.Description.Endpoints[0].Behaviors.Add(new WebHttpBehavior { HelpEnabled = true });
return host;
}
问题是如何防止通道在错误处理程序中出现故障。