Thursday, April 1, 2010

I’m a developer that hate “cut and paste”. While it get the lines of code per day up, it is excessively and needlessly expensive. For AspNet, I tend to favor minimal code pages (if possible code-less pages) which often end up with a Asp:??DataSource working with Grids, DropDownLists, etc.

One of the issues is error handling – an item that can often double the code in an application. In some cases it is possible to write a few static methods and have error handling implemented across a entire website with no risk of some item not having error handling. This code example deals with ObjectDataSource (what is often used for calls to WCF)

I use Master Pages, so life is simple with the addition of a single line in the Master Page(s) as shown below:

There was one gotcha – the sender is NOT the ObjectDataSource control but an isolated ObjectDataSourceView, so we have to grab the page through the handler and then search it for where we display the message.

In the above case, you are displaying the exception message to the user which is normally not the best practice. A better recommendation would be to use custom obfuscation text for each type of exception expected using a switch, with a default of “Unexpected Error” for what does not match.

You now have site-wide consistent error handling that is strictly enforced (by code).