gpt4 book ai didi

C# : Better way to code this?

转载 作者:太空狗 更新时间:2023-10-30 00:21:28 27 4
gpt4 key购买 nike

我有一段代码来处理我的应用程序中的异常,它使用 if/else block 来获取消息内容。
我的代码如下:

// 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 block )并假设“异常”对象最终派生自异常,您可以稍微简化一下代码

// 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());

关于C# : Better way to code this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5153775/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com