我有一个代码块来处理我的应用程序中的异常,它使用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());
Run Code Online (Sandbox Code Playgroud)
这已从原始版本改进,但只是想看看是否有更简洁,更可重用的解决方案.
在此先感谢
马丁
假设这是一个传递异常对象的例程(并没有直接参与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());
Run Code Online (Sandbox Code Playgroud)