Is it possible to overload the try/catch statements in C#? Failing that, is it possible to inherit and make similar functionality?
We are adding ELMAH to an existing web application and the code uses try/catches extensively, displaying errors in the validation summary instead of displaying error pages. As the errors are being caught in the catch statement ELMAH assumes that the errors are being dealt with; in actuality they are just being displayed in a more presentable manner.
Here is a sample of what it is doing:
try
{
//code here...
}
catch (Exception ex)
{
customValidatorError.IsValid = false;
customValidatorError.ErrorMessage = ex.Message;
}
Ideally the overload would just tell Elmah to add the exception to the logs via ErrorSignal.FromCurrentContext().Raise(e);
Due to the frequency this technique is used in the project I would prefer not to add that code to each and every time it is used. It is also beyond the scope of the project to add custom error pages for each error page instead of adding the errors to the validation summary.
As you’ve found, wrapping everything in try/catch usually doesn’t turn out to be what you really want. You end up “swallowing” exceptions that you probably want to log somewhere. If you do want to show the exception message on the page with a custom validator, you should probably re-throw the exception so that you can bubble that up. ASP.NET will allow you to setup “global” error handling. If you want to swallow the exceptions, you can do that in a single place. If you want to signal ELMAH or log them using another method, you can do so in a single place. This keeps your exception handling DRY.