【发布时间】:2011-03-01 20:00:13
【问题描述】:
我有一个代码块来处理我的应用程序中的异常,它使用 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());
这已经从原始版本进行了改进,但只是想看看是否有针对此代码的更简洁、更可重用的解决方案。
提前感谢
马丁
【问题讨论】:
-
你为什么不
switch()你的expType?这会给你的代码带来更多的结构。 -
我试过了,但你不能使用非整数类型的 switch,这就是我没有使用那个结构的原因。
-
@Martin:你不能在
Types 上switch。 -
@m.edmondson - 什么不正确?你不能打开非整数类型?
-
@Martin S - 抱歉我看错了,以为你输入了整数类型 :-)
标签: c# if-statement