开发者

Custom exception handling in WCF Service and Client

What you think about this approach:

Fault helper:

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

Server side usage:

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

Client side开发者_C百科 usage:

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


Interesting idea. It saves you decorating your services with 100's of individual exceptions.

But why not just have exception as a property of WcfHwServiceFault?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜