2016-04-07 3 views
0

WCFのFaultContractにUser Define Exceptionを含めたいと思います。 私のWCFアプリケーションでは、FaultContractにExceptionインスタンス/ UserDefine例外インスタンスをカプセル化したいと思います。 下記の私のUserDefine Exceptionを見つけてください。WCFのFaultContractに実際の例外またはカスタム例外を含める方法

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)); 
     } 

tryブロックキャッチCustomException(のRecordNotFoundException)以下のようなサービスで投げる例外だが、クライアントにその例外を送信することができません。あなたは、SOAPクライアントは、あなたのcatchブロックをするために最善FaultException<T>

catch (FaultException<MathFault> e) 
{ 
    Console.WriteLine("FaultException<MathFault>: Math fault while doing " + e.Detail.operation + ". Problem: " + e.Detail.problemType); 
    client.Abort(); 
} 

をキャッチする必要がある例外タイプ

[OperationContract] 
[FaultContract(typeof(MathFault))] 
int Divide(int n1, int n2); 

を期待する知っているように、あなたのOperationContract方法にFaultContract属性を追加する必要が

答えて

0

各例外タイプごとにDataContractを1つにまとめようとするのではなく、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の実装を含めたい場合、あなたはSOAPクライアントは、タイプを認識しているように、KnownType属性を使用する必要があるかもしれません:あなたの迅速な対応のための

​​
+0

おかげグレン、しかし、私はFaultContract(あなたの例ではMathFault)に独自のExceptionを含めたいので、クライアントは実際の例外や操作や問題のような他のカスタムデータを得ることができます。 – Sourabh

+0

Shortでは、実際の例外をシリアル化して、それをクライアントに送っています。 – Sourabh

+0

@Sourabhああ、私は参照してください。 SOAPサービスでは、DataContractを介してクライアントが認識しているカスタムタイプのみを送信できます。 KnownType属性を追加すると、これが役に立ちます。 –

関連する問題