如何在WCF的FaultContract中包含实际的异常或自定义异常

时间:2016-04-07 15:08:14

标签: c# wcf faultexception

我想在WCF的FaultContract中包含一个用户定义异常。 在我的WCF应用程序中,我想在FaultContract中封装Exception实例/ UserDefine异常实例。 请找到我的以下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 StoreProcNotFoundException : UserExceptions
{
    public string innerExp { get; set; }
    public StoreProcNotFoundException(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),但它无法将该异常发送到客户端。

1 个答案:

答案 0 :(得分:0)

您需要将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(StoreProcNotFoundException))]
public class ExceptionFault
{ 
    [DataMember]
    public UserExceptions Exception { get; set; }

    public ExceptionFault(UserExceptions ex)
    {
        this.Exception = ex;
    }
}