Microsoft Enterprise Library Custom Exception Handler

By Michael Detras

Using the Microsoft Enterprise Library, we can create a custom exception handler where the exceptions will be routed. We can do some logging, or change the exception to throw so that the error message is not very technical to a regular user.

Here is an example that changes the error message to be thrown.

[ConfigurationElementType(typeof(CustomHandlerData))]
public class CustomExceptionHandler : IExceptionHandler
{
    private static Dictionary<Type, string> ExceptionMessages = new Dictionary<Type, string>()
    {
        { typeof(EndpointNotFoundException), "The application can't find the service. " +
            "Ensure that the client computer is connected to the server, and the server and its " +
            "services are running."}
    };

    public CustomExceptionHandler(NameValueCollection parameters)
    {
    }

    public Exception HandleException(Exception exception, Guid handlingInstanceId)
    {
        Exception exceptionToThrow = new Exception(ExceptionMessages[typeof(Exception)]);
        return exceptionToThrow;
    }
}

Microsoft Enterprise Library Custom Exception Handler  (1053 Views)