I have a block of code to handle exceptions in my application, which uses an if/else block to obtain the message content.
My code is as follows:
// define variable to hold exceptions...
var exceptionMessage = new StringBuilder();
// based on the exception type...
if (expType == typeof(EntityValidationException))
{
// append the relevant message to the text...
exceptionMessage.Append(exception.InnerException.Message);
}
else if (expType == typeof(ValidationException))
{
// This is the type of error generated when entities are validated
var validationException = (ValidationException)exception;
exceptionMessage.Append(validationException.InnerException.Message);
}
else if (expType == typeof(DomainSecurityException))
{
// These are security breaches
var domainSecurityException = (DomainSecurityException)exception;
exceptionMessage.Append(domainSecurityException.InnerException.Message);
}
else if (expType == typeof(DomainInternalMessageException))
{
// These are the type of errors generated a System.Exception occurs and is
// converted by the exception handling policy to a more friendly format
var domainInternalMessageException = (DomainInternalMessageException)exception;
exceptionMessage.Append(domainInternalMessageException.ExceptionMessage);
}
else
{
exceptionMessage.AppendFormat(ErrorMessagesRes.Standard_Error_Format, "Unknown error", exception.InnerException.Message);
}
// this shows the message as an alert popup...
this.DisplayJavascriptMessage(exceptionMessage.ToString());
This has been improved from the original version, but just want to see if there is a neater, more re-usable solution to this code.
Thanks in advance
Martin
Assuming that this is a routine which gets passed an exception object (and is not directly involved in a try catch block) and assuming the "exception" object derives eventually from Exception, you could concise your code a bit to do
// define variable to hold exceptions...
var exceptionMessage = new StringBuilder();
// based on the exception type...
if (exception is EntityValidationException || exception is ValidationException || exception is DomainSecurityException)
{
// append the relevant message to the text...
exceptionMessage.Append(exception.InnerException.Message);
}
else if (expType == typeof(DomainInternalMessageException))
{
// These are the type of errors generated a System.Exception occurs and is
// converted by the exception handling policy to a more friendly format
var domainInternalMessageException = (DomainInternalMessageException)exception;
exceptionMessage.Append(domainInternalMessageException.ExceptionMessage);
}
else
{
exceptionMessage.AppendFormat(ErrorMessagesRes.Standard_Error_Format, "Unknown error", exception.InnerException.Message);
}
// this shows the message as an alert popup...
this.DisplayJavascriptMessage(exceptionMessage.ToString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With