开发者

Passing Exception as a part of response in WCF

I have somewhat unconventional use of exceptions in my app. If an exception happens in the method, I pass it as a part of the result object, something like this:

public class MethodResponse
{
  public List<Exception> Errors {get; set;}
  public int SomeResult {get; set;}
}

Now, I'm separating Business layer and UI layer using WCF, and I'm getting an issue - WCF doesn't like Exception objects and if one is present in Errors list, it crashes the service. I did some 开发者_开发技巧research and it looks like WCF can't serialize Exception class.

Is there a workaround?


You need to remember one big issue: WCF is supposed to be interoperable - .NET exceptions aren't - those are .NET only. Java or Ruby won't be able to handle your exceptions....

Anything that you pass between your WCF server and client must be XML serializable. So basically, what you need to do, is wrap those exceptions into interoperable SOAP faults - those are indeed interoperable and serializable. Or you need to define your own "WCFError" type that encapsulates all the information you need from the .NET exception - things like error code, error message etc. - and on your WCF server, implement the IErrorHandler interface and turn all .NET exceptions into instances of your own error class and pass that back to the caller.

Hope that helps at least a bit - there's no magic bullet - you just need to be aware of what WCF can and cannot handle - and why.


You may want to consider whether the approach you are taking is the correct one. Exceptions serve a specific purpose in the .NET Framework; they're not designed to be data transfer objects. What information do you need, relating to the exceptions, to be transferred between from the Business layer back to the UI layer? You may want to consider creating a DTO Error class that contains the information from each exception that you need to transfer, then return a List of your DTO error objects.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜