as the title, should i catch exception on server side?
views:
85answers:
3I would like to divide the exceptions in following 2 types because I am not sure which ones you are talking about:
WCF communication exceptions:
These exceptions are not likely to trouble your server side application. So you need not worry about them. You just need to be careful in client application.
Application Exceptions:
(Obviously) You do need to catch them otherwise your server side application will crash.
Yes you should - by all means!
First of all, uncaught exceptions on the server side will "fault" the channel, e.g. put the channel between the client and server into "panic mode" - no more calls possible, you need to close (or abort) the channel from the client side and re-establish the connection.
Second, of course, an unhandled exception will crash your server code - however, by default, your WCF calls should be "per-call" anyway, which means, each request coming in will get a brand-new, freshly instantiated object of your server class, and at the end of the call, it will be disposed of anyway. So that's really not all that bad...
There's an interface in WCF called IErrorHandler
which you can implement on your server side. What it provides is the ability to catch any exceptions, and turn them into "interoperable" SOAP faults, which will be sent back over the communication channel without causing it to go into panic mode.
There are several IErrorHandler
implementations out there that basically allow you to dynamically plug that in as a service behavior - either in the server's config, or in your service class code as an attribute. Check out this blog post for one of those samples (there are many more out there - just google for them).
Routine exceptions are expected; it would be better to bubble them as faults (the WCF term - look for FaultException
), but either way the exception will simply get translated onto the wire and handled by the client. WCF clients really don't like to get exceptions, and this is usually terminal for a proxy (the client should clean up their existing proxy and spin up a new one to get a new session etc). But your server process (minus the borked session) will keep running and serving requests.
There are of course a category of pretty nasty and server-fatal exceptions - stack overflows, out of memory, thread-abort, etc. But there isn't much you can do about those anyway!