2010-09-03 135 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