2010-09-03 134 views
1

你怎麼看待這種做法:自定義異常處理和客戶

故障幫手:

[Serializable] 
public class WcfHwServiceFault 
{ 
    private readonly Guid _guid; 
    private readonly byte[] _data; 

    private WcfHwServiceFault(Guid guid, byte[] data) 
    { 
     _guid = guid; 
     _data = data; 
    } 

    public static WcfHwServiceFault Create(Exception ex) 
    { 
     var formatter = new SoapFormatter(null, new StreamingContext(StreamingContextStates.CrossMachine)); 
     var ms = new MemoryStream(); 
     formatter.Serialize(ms, ex); 

     return new WcfHwServiceFault(ex.GetType().GUID, ms.GetBuffer()); 
    } 

    public Exception Get() 
    { 
     var formatter = new SoapFormatter(null, new StreamingContext(StreamingContextStates.CrossMachine)); 
     var ms = new MemoryStream(_data); 
     return (Exception)formatter.Deserialize(ms); 
    } 
} 

服務器端應用:

try 
{ 
    ... 
} 
catch (Exception ex) 
{ 
    throw new FaultException<WcfHwServiceFault>(WcfHwServiceFault.Create(ex)); 
} 

客戶端使用情況:

try 
{ 
    Channel.DoSomeMethod(...); 
} 
catch (FaultException<WcfHwServiceFault> ex) 
{ 
    throw ex.Detail.Get(); 
} 
catch (CommunicationException ex) 
{ 
    throw new ApplicationException("Communication error.", ex); 
} 
+1

這是什麼意思?你爲什麼使用'ApplicationException'?你不知道你不再使用它嗎?另外,你使用運行時序列化的原因是什麼?如果異常不是可序列化的呢?你有沒有真正想解決的問題? – 2010-09-03 02:33:53

+0

2 PostMan:此代碼是可編譯和可運行的: catch(FaultException ex) throw ex.Detail.Get(); } catch(CommunicationException ex) { }拋出新的ApplicationException(「Communication error。」,ex); } – SeeSharp 2010-09-03 03:11:30

+0

2 John Saunders: 1.客戶端通過通用接口使用業務邏輯並使用適當的異常(本地)集合。 2.然後我們通過wcf添加代理,但客戶端像以前一樣使用相同的接口和異常。 3.所有業務邏輯的異常都是可序列化的,但我想你會問很多問題。謝謝。 PS對不起,如果我的英文不太清楚。 – SeeSharp 2010-09-03 03:26:17

回答

0

有趣的想法。它可以爲您節省數百個單獨例外的服務。

但是,爲什麼不僅僅作爲WcfHwServiceFault的屬性出現異常?

+0

此屬性在客戶端(在WCF解串器之後)爲空,因爲它們沒有適當的屬性。 – SeeSharp 2010-09-03 19:47:48

+0

你不能用相應的屬性來標記它嗎? – 2010-09-03 20:11:23

+0

通過http不起作用。 – SeeSharp 2010-09-06 08:03:13