我正在尝试设计一种简单易用的错误处理设计模式,用于.NET WCF服务(特别是Silverlight启用的WCF服务)。如果服务方法中抛出异常,则Silverlight应用程序将看到一个CommunicationException,指明“远程服务器返回了一个错误:NotFound——>”,以及可能的堆栈跟踪(具体取决于您的设置),但这完全没有用,因为它并没有告诉您实际的错误,通常真正的错误不是“NotFound”。
通过阅读有关Web服务和WCF服务以及异常的资料,您需要抛出SOAP/WCF标准异常,例如FaultException或SoapException。因此,对于WCF服务,您需要在每个方法中包装try catch,捕获每个异常,将其包装在FaultException中并抛出。至少这是我的理解,请纠正我如果我错了。
因此,我创建了自己的设计模式:
通过阅读有关Web服务和WCF服务以及异常的资料,您需要抛出SOAP/WCF标准异常,例如FaultException或SoapException。因此,对于WCF服务,您需要在每个方法中包装try catch,捕获每个异常,将其包装在FaultException中并抛出。至少这是我的理解,请纠正我如果我错了。
因此,我创建了自己的设计模式:
[ServiceContract(Namespace = "http://MyTest")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DataAccess
{
/// <summary>
/// Error class, handle converting an exception into a FaultException
/// </summary>
[DataContractAttribute]
public class Error
{
private string strMessage_m;
private string strStackTrace_m;
public Error(Exception ex)
{
this.strMessage_m = ex.Message;
this.strStackTrace_m = ex.StackTrace;
}
[DataMemberAttribute]
public string Message
{
get { return this.strMessage_m; }
set { this.strMessage_m = value; }
}
[DataMemberAttribute]
public string StackTrace
{
get { return this.strStackTrace_m; }
set { this.strStackTrace_m = value; }
}
//Convert an exception into a FaultException
public static void Throw(Exception ex)
{
if (ex is FaultException)
{
throw ex;
}
else
{
throw new FaultException<Error>(new Error(ex));
}
}
}
[OperationContract]
[FaultContract(typeof(Error))]
public void TestException()
{
try
{
throw new Exception("test");
}
catch (Exception ex)
{
Error.Throw(ex);
}
}
}
长话短说,我的Silverlight应用程序仍然没有正确的错误提示。我检查了AsyncCompletedEventArgs.Error对象,它仍然包含一个通用错误的CommunicationException对象。请帮我设计一个简单的设计模式,以便我可以轻松地从服务中抛出正确的异常,并在应用程序中轻松地捕获它。