【问题标题】:Custom exception handling in WCF Service and ClientWCF 服务和客户端中的自定义异常处理
【发布时间】:2011-04-07 15:42:13
【问题描述】:

您对这种方法的看法:

故障助手:

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

【问题讨论】:

  • 这有什么意义?你为什么使用ApplicationException?你不知道你不再使用它了吗?另外,您使用运行时序列化的原因是什么?如果异常不可序列化怎么办?您有真正想要解决的问题吗?
  • 2 PostMan:这段代码是可编译和可运行的:catch (FaultException ex) { throw ex.Detail.Get(); } catch (CommunicationException ex) { throw new ApplicationException("Communication error.", ex); }
  • 2 John Saunders: 1. 客户通过通用接口和一组适当的异常(本地)使用业务逻辑。 2. 然后我们在 wcf 上添加代理,但客户端和以前一样使用相同的接口和异常。 3. 业务逻辑的所有异常都会被序列化,但我认为你问的问题非常好。谢谢。 PS对不起,如果我的英语不清楚。

标签: .net exception-handling wcf wcf-client


【解决方案1】:

有趣的想法。它可以节省您用 100 个单独的例外来装饰您的服务。

但是为什么不把异常作为 WcfHwServiceFault 的一个属性呢?

【讨论】:

  • 此属性在客户端(在 WCF 反序列化器之后)将为空,因为它们没有适当的属性。
猜你喜欢
  • 2023-03-19
  • 2010-11-25
  • 1970-01-01
  • 1970-01-01
  • 2018-09-18
  • 2015-05-24
  • 2021-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多