[英]C# : Better way to code this?
我有一個代碼塊來處理我的應用程序中的異常,它使用if / else塊來獲取消息內容。
我的代碼如下:
// 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());
這已從原始版本改進,但只是想看看是否有更簡潔,更可重用的解決方案。
提前致謝
馬丁
假設這是一個傳遞異常對象的例程(並沒有直接參與try catch塊)並假設“異常”對象最終從Exception派生,你可以簡單地簡化你的代碼
// 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());
var exceptionMessage = new StringBuilder();
try
{
}
catch(EntityValidationException exc)
{
exceptionMessage.Append(exc.InnerException.Message);
}
catch(ValidationException exc)
{
exceptionMessage.Append(exc.InnerException.Message);
}
....
確保catch塊的順序從最不通用到最通用。
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 => ...);
每當我看到那些if else if
語句我認為這必須更容易。 在某些情況下,switch語句可以提供幫助,但正如此問題已經說明的那樣,無法打開Type。
所以我經常使用的另一種解決方法是某種Dictionary<Type, something>
。 something
取決於我想做什么。 對於你的案例,最好的匹配構造可能類似於Dictionary<Type, Func<Exception, string>>
,它可以在你的情況下使用,如下所示:
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
}
因此,通過這種結構,您無需將所有智能放入一個大的if-else語句中。 相反,您可以將它們放在單獨的函數中(可能在不同的類中),以便更好地組織如何處理您希望支持的每種類型。
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);
有點壓縮,沒有評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.