我想在WCF的FaultContract中包含一个用户定义异常。在我的WCF应用程序中,我想在FaultContract中封装Exception实例/UserDefine Exception实例。请查找我下面的UserDefine异常。
public class UserExceptions : Exception
{
public string customMessage { get; set; }
public string Result { get; set; }
public UserExceptions(Exception ex):base(ex.Message,ex.InnerException)
{
}
}
public class RecordNotFoundException : UserExceptions
{
public RecordNotFoundException(Exception ex): base(ex)
{
}
}
public class StoredProcNotFoundException : UserExceptions
{
public string innerExp { get; set; }
public StoredProcNotFoundException(Exception ex,string innerExp)
: base(ex)
{
this.innerExp = innerExp;
}
}
[DataContract]
public class ExceptionFault
{
[DataMember]
public UserExceptions Exception { get; set; }
public ExceptionFault(UserExceptions ex)
{
this.Exception = ex;
}
}
我在下面的服务中抛出异常
try
{
//Some Code
//Coding Section
throw new RecordNotFoundException(new Exception("Record Not Found"));
//Coding Section
}
catch (RecordNotFoundException rex)
{
ExceptionFault ef = new ExceptionFault(rex);
throw new FaultException<ExceptionFault>(ef,new FaultReason(rex.Message));
}
catch (Exception ex)
{
throw new FaultException<ExceptionFault>(new ExceptionFault((UserExceptions)ex),new FaultReason(ex.Message));
}
尝试阻止catchCustomException(RecordNotFoundException),但无法将该异常发送到客户端。
您需要将FaultContract
属性添加到OperationContract
方法中,以便SOAP客户端知道会出现异常类型
[OperationContract]
[FaultContract(typeof(MathFault))]
int Divide(int n1, int n2);
您的捕获块需要捕获FaultException<T>
catch (FaultException<MathFault> e)
{
Console.WriteLine("FaultException<MathFault>: Math fault while doing " + e.Detail.operation + ". Problem: " + e.Detail.problemType);
client.Abort();
}
最好为每个异常类型都有一个DataContract
,而不是试图将它们全部打包为一个DataContract
[DataContract]
public class MathFault
{
private string operation;
private string problemType;
[DataMember]
public string Operation
{
get { return operation; }
set { operation = value; }
}
[DataMember]
public string ProblemType
{
get { return problemType; }
set { problemType = value; }
}
}
如果您想在DataContract中包含UserExceptions的实现,那么您可能需要使用KnownType属性,以便SOAP客户端了解以下类型:
[DataContract]
[KnownType(typeof(RecordNotFoundException))]
[KnownType(typeof(StoredProcNotFoundException))]
public class ExceptionFault
{
[DataMember]
public UserExceptions Exception { get; set; }
public ExceptionFault(UserExceptions ex)
{
this.Exception = ex;
}
}