C #: Best way to code this?

I have an exception code block in my application that uses an if / else block to get the contents of the message.
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 tidier, more reusable solution for this code.
Thanks in advance Martin

+4
source share
5 answers

Assuming this is a routine that receives an exception object (and does not participate directly in the catch try block), and assuming that the exception object ultimately gets an exception from Exception, you can shorten the code a bit to make

 // 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()); 
+5
source
  var exceptionMessage = new StringBuilder(); try { } catch(EntityValidationException exc) { exceptionMessage.Append(exc.InnerException.Message); } catch(ValidationException exc) { exceptionMessage.Append(exc.InnerException.Message); } .... 

Make sure the catch blocks are in the correct order from minimum to most common.

+2
source
 public static Exception On<T>(this Exception e, Action<T> action) { if(e is T) action((T)e); return e; } exception. On<ValidationException>(e => exceptionMessage.Append(e.InnerException.Message)). On<DomainInternalMessageException>(e => ...); 
+2
source

Whenever I see those if else if sentences, I find it easier to do this. In some cases, the switch statement may help, but as this question has already been pointed out, it is not possible to include Type.

So another workaround that I usually use is a kind of Dictionary<Type, something> . Where something depends on what I would like to do. Perhaps a suitable construct for your case will be similar to Dictionary<Type, Func<Exception, string>> , which can be used in your case something like this:

 Dictionary<Type, Func<Exception, string>> _FunctorsForType; private void InitializeFunctorsForType() { _FunctorsForType = new Dictionary<Type, Func<Exception, string>>(); // Add a normal function _FunctorsForType.Add(typeof(ArgumentException), (Func<Exception, string>)ForArgumentException); // Add as lambda _FunctorsForType.Add(typeof(InvalidCastException), (ex) => { // ToDo: Whatever you like return ex.Message; }); } private string ForArgumentException(Exception ex) { var argumentException = ex as ArgumentException; if (argumentException == null) { throw new ArgumentException("Exception must be of type " + typeof(ArgumentException).Name); } // ToDo: Whatever you like return ex.Message; } private void Usage(Type type) { Func<Exception, string> func; if (!_FunctorsForType.TryGetValue(type, out func)) { throw new ArgumentOutOfRangeException("Exception type " + type.Name + " is not supported."); } var message = func(new NullReferenceException()); // ToDo: Whatever you have to do with your message } 

Thus, with this design, you do not need to inject all your intelligence into a large if-else statement. Instead, you can put them in separate functions (possibly in different classes) to get a better organization of how to handle each type that you like to support.

+1
source
 string exceptionMessage; if (expType == typeof(EntityValidationException) || expType == typeof(ValidationException) || expType == typeof(DomainSecurityException)) exceptionMessage = exception.InnerException.Message; else if (expType == typeof(DomainInternalMessageException)) exceptionMessage = ((DomainInternalMessageException)exception).ExceptionMessage; else exceptionMessage = string.Format(ErrorMessagesRes.Standard_Error_Format, "Unknown error", exception.InnerException.Message); this.DisplayJavascriptMessage(exceptionMessage); 

A bit compressed and no comment.

0
source

Source: https://habr.com/ru/post/1341794/


All Articles