Exception handling in user controls that don’t catch critical exception that can leave a unsecure and instable server if they are catch. And also fix the FxCop rule “CA1031 DoNotCatchGeneralExceptionTypes”.
Usage
try
{
// Do stuff
} catch (Exception ex)
{
if (!ExceptionHandler.TryHandleException(ex))
{
throw;
}
// Log error
// Handle all errors, for user controls set for example Visible = false
}
Implementation
/// <summary>
/// The ExceptionHandler is a class to make it easier for the developer
/// to catch exceptions that is not critical for the application.
/// <example>
/// Example the developer wants to develop a user control that should
/// not be visible when something goes wrong – and not crash the whole web page.
/// </example>
/// </summary>
public class ExceptionHandler
{
/// <summary>
/// A list of exceptions those are not critical
/// for the applications runtime environment.
/// <remarks>
/// This list is non finished list it must be updated when
/// the code are updated.
/// </remarks>
/// <example><code>
/// NullReferenceException is an exception can’t set the application
/// in an inconsistent state
///
/// But
/// OutOfMemory is an exception that absolutely sets the application
/// in an inconsistent state
/// </code></example>
/// </summary>
private static readonly Type[] NonFatalExceptions = new[]
{
typeof(NullReferenceException),
typeof(IndexOutOfRangeException),
typeof(ArgumentException),
typeof(ArithmeticException),
typeof(SerializationException),
typeof(WebException),
typeof(IOException),
typeof (ApplicationException)
};
/// <summary>
/// Tries to handle the given exception and returns true
/// if it's a non critical exception for the application.
/// </summary>
/// <param name="ex">The exeption to check.</param>
/// <returns><c>True</c> if the exception can be handle;
/// otherwise <c>false</c>.</returns>
/// <code>
/// try
/// {
/// throw new NullReferenceException();
/// } catch (Exception ex)
/// {
/// if (!ExceptionHandler.TryHandleException(ex))
/// {
/// throw;
/// }
/// }
/// </code>
public static bool TryHandleException(Exception ex)
{
Type exceptionType = ex.GetType();
foreach(Type t in NonFatalExceptions)
{
if (t.IsAssignableFrom(exceptionType))
{
return true;
}
}
return false;
}
}