我想在WCF的FaultContract中包含一个用户定义的异常。在我的WCF应用程序中,我想将异常实例/用户定义异常实例封装在FaultContract中。请查找我的以下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));
}尝试块捕获CustomException(RecordNotFoundException),但它无法将异常发送到客户端。
发布于 2016-04-07 23:14:49
您需要将FaultContract属性添加到OperationContract方法中,以便SOAP客户端知道需要异常类型
[OperationContract]
[FaultContract(typeof(MathFault))]
int Divide(int n1, int n2);catch块需要捕获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;
}
}https://stackoverflow.com/questions/36480237
复制相似问题