Extensibility is the key feature of any Enterprise Library Application Block and hence, this block is extensible too. The Exception Handling block provides two areas for extensions, Exception Handler and Exception Formatter. We have already understood the concept of an exception handler and have also used many out-of-the-box handlers. Implementing a custom handler is very easy: we have to implement the IExceptionHandler
interface and provide our custom implementation of the HandleException
method. To understand and learn to implement a custom exception handler, let us create an exception handler that displays a message box to the user in a Windows Forms application.
The following code snippet provides the implementation of a custom exception handler that displays a message box whenever it receives a request to handle exception:
[ConfigurationElementType(typeof(CustomHandlerData))] public class WindowsMessageExceptionHandler : IExceptionHandler { public WindowsMessageExceptionHandler(NameValueCollection ignore) { } public Exception HandleException(Exception exception, Guid handlingInstanceId) { MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return exception; } }
The WindowsMessageExceptionHandler
class inherits from the IExceptionHandler
interface and provides implementation for the HandleException
method; this method shows a message box with the exception message. The custom exception handler implementation is decorated with the ConfigurationElementType
attribute with the CustomHandlerData
type as parameter; this essentially indicates the configuration object type.
Configuration for the custom exception handler is similar to that for other handlers; we just need to add the WindowsMessageExceptionHandler
in the configuration editor. Right-click on the exception type and click on Add Handlers | Add Custom Exception Handler. In the selection dialog, select the WindowsMessageExceptionHandler
class.
The following screenshot shows the configuration screen for Add Custom Exception Handler:
The following screenshot shows WindowsMessageExceptionHandler
added to the configuration editor:
We are done with our implementation and configuration of the custom exception handler. While handling exceptions in code using the specific policy mapped with the custom handler, it will display a message box to the user with the error message.
3.145.17.140