Take Control of Web Service Exceptions

Craig Andera posts a technique for handling exceptions thrown by a webservice. He takes the approach of adding a try catch block to each method.

A while ago I tackled the same problem, but I was unhappy with the idea of wrapping every inner method call with a try catch block. I figured there had to be a better way. Since SOAP is simply XML being sent over a wire, I figured there had to be a way for me to hook into the pipeline rather than modify my code.

What I came up with is my Exception Injection Technique Using a Custom Soap Extension. This allows you to simply add an additional attribute to each web method as in the sample below and have full control over how exceptions are handled and sent over the wire.

[WebMethod, SerializedExceptionExtension]

public string ThrowNormalException()

{

    throw new ArgumentNullException("MyParameter",
        "Exception thrown for testing purposes");

}

Read about the technique here and feel free to adapt it to your purposes.

What others have said

Requesting Gravatar... Jeff Atwood Nov 02, 2005 4:09 AM
# re: Take Control of Web Service Exceptions
Yes, I reached the same conclusion:

Throwing Better .NET Exceptions with SOAP and HTTP
http://www.codinghorror.com/blog/archives/000108.html
Requesting Gravatar... Haacked Nov 02, 2005 5:35 AM
# re: Take Control of Web Service Exceptions
Nice! I didn't see your article when I was researching my solution.
Requesting Gravatar... Maths Mar 26, 2007 12:08 PM
# re: Take Control of Web Service Exceptions
This seem to be the best approach. Now, the infrastructure code can take care of managing exception. I am already planning to use this in my current project.
Requesting Gravatar... Maths Mar 26, 2007 12:14 PM
# re: Take Control of Web Service Exceptions
This seem to be the best approach. Now, the infrastructure code can take care of managing exception. I am already planning to use this in my current project.

What do you have to say?

(will show your gravatar)
Please add 6 and 2 and type the answer here: