在我最近的项目(WCF REST 服务)中,我使用了WebServiceHostFactory并且我仍然能够使用IErrorHandler来实现这一点。在下面查找示例
我创建了一个可以序列化并发送回客户端的类 ExceptionInfo。
[Serializable]
public class ExceptionInfo
{
public string ExceptionType { get; set; }
public string ExceptionMessage { get; set; }
public string StackTrace { get; set; }
}
并实现自定义错误处理程序
[DataContract]
public class MyCustomServiceErrorHandler : IErrorHandler
{
#region IErrorHandler Members
/// <summary>
/// This method will execute whenever an exception occurs in WCF method execution
/// </summary>
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
var exceptionInfo = new ExceptionInfo();
if (error is MyCustomException)
exceptionInfo.ExceptionType = error.Type.ToString();;
else
exceptionInfo.Type = "Unhandled Exception";
exceptionInfo.ExceptionMessage = error.Message;
exceptionInfo.StackTrace = error.StackTrace;
var faultException = new FaultException<ExceptionInfo>(exceptionInfo);
object detail = faultException.GetType().GetProperty("Detail").GetGetMethod().Invoke(faultException, null);
fault = Message.CreateMessage(version, "", detail, new DataContractSerializer(detail.GetType()));
var webBodyFormatMessageProp = new WebBodyFormatMessageProperty(WebContentFormat.Xml);
fault.Properties.Add(WebBodyFormatMessageProperty.Name, webBodyFormatMessageProp);
var httpResponseMessageProp = new HttpResponseMessageProperty();
httpResponseMessageProp.Headers[HttpResponseHeader.ContentType] = "application/xml";
httpResponseMessageProp.StatusCode = HttpStatusCode.BadRequest;
httpResponseMessageProp.StatusDescription = exceptionInfo.ExceptionMessage;
fault.Properties.Add(HttpResponseMessageProperty.Name, httpResponseMessageProp);
}
/// <summary>
/// Performs error related behavior
/// </summary>
/// <param name="error">Exception raised by the program</param>
/// <returns></returns>
public bool HandleError(Exception error)
{
// Returning true indicates that an action(behavior) has been taken (in ProvideFault method) on the exception thrown.
return true;
}
现在您可以使用上面的处理程序来装饰您的服务。
[ServiceContract]
[ServiceErrorBehavior(typeof (MyCustomServiceErrorHandler))]
public class LoginService : ServiceBase
{}
在客户端,您可以检查响应的 HttpStatusCode 是否 != Ok 并将响应反序列化为 ExceptionInfo 类型并显示在消息框中或按要求处理。
希望这可以帮助。