Friday, June 9, 2017

WCF Exception type

Framework 4.0

As you know, when you throw an exception in a WCF endpoint, it is always returned to the calling code as a System.Exception. I would like to have the calling code understand whether the exception is deliberately thrown by my code (ie the account doesn't have enough funds to cover the purchase) or is thrown by something external to my logic (ie the sql command timed out).

I would normally use the exception type to do this, perhaps my making all the deliberate exceptions ApplicationExceptions. Unfortunately the exception I throw always gets converted to a System.Exception by the time it reaches the calling code. It's great that an exception thrown in the WCF endpoint causes an exception to be thrown in the calling code, but it would be even better if the exception type were the same.

Although I have not found a way to do exactly this, I have found a simple way to discover the type of the original exception.

If you look at the exception returned you can see a [Detail] property which has a [Type] property that is a string containing the full type of the original exception ie "System.ApplicationException". However you will soon find that both [Detail] and [Type] are not accessible. 

Here is a line of code that gets the original exception type anyway.

Dim exBase As String = ex.GetType().GetProperty("Detail").GetValue(ex, Nothing).Type

No comments:

Post a Comment