I was asked recently if errors in an application should be handled in the business layer or in the UI. The answer to this is simple: Neither. Doing so is repetitive and unproductive. Error handling should be an automatic part of your infrastructure.

It may seem that error handling is not something that can be performed automatically. But this is due to a broader definition of error than is applicable here. Conditions that are expected and probable during your applications execution are not errors, they’re use cases. If may be a user error that they have entered an invalid value, or a network issue that causes your web browser to be unable to contact a website. But these are expected conditions that an application must deal with. Your application stack should have a clean way of reporting that requested operations could not be completed and this should be tested appropriately.

A genuine application error is caused by coding errors or violations of fundamental assumptions that your application works with. If your validation code allows an out of range value that causes a divide by zero this is an application error. If you cannot find an essential application file this is an application error. Such an error will almost certainly result in an exception. Handling these exceptions in the business specific code is not helpful. You can’t anticipate these errors as you would otherwise have prevented them. Placing duplicate error handling code throughout your codebase is a maintenance overhead and does not really provide any value. Instead the framework on which you build your application should handle these cases.

If you are building a web application on ASP.NET (including ASP.NET MVC) then ELMAH is an excellent tool for providing this functionality: http://code.google.com/p/elmah/. Many GUI application frameworks will provide the ability to handle errors or you can hook into the AppDomain events invoked on unhandled exceptions. In a service process some simple dynamic proxies coupled with dependency injection can wrap exception handling logic around every service invocation without requiring any modification of the business code. Some frameworks such as the NServiceBus Host provide logging capabilities built in that require only configuration.

What we are aiming for therefore is that handling of genuine errors in the application is automatic and comprehensive. This is not possible if we start polluting our business or UI code with attempts to handle the unhandleable. Build your application so that this handling happens so transparently in the background that you can generally forget its even there.