我的代码看起来是这样的:
try
{
foo();
}
catch (SecurityTokenValidationException ex)
{
Logger.ErrorFormat(ex.Message, ex);
return null;
}
catch (SignatureVerificationFailedException ex)
{
Logger.ErrorFormat(ex.Message, ex);
return null;
}但是代码分析报告说"Avoid Excessive Complexity"
有什么指示吗?
发布于 2016-07-14 12:26:43
如果使用的是C# 6,则可以使用异常筛选将处理限制在两种类型上。
try
{
foo();
}
catch (Exception ex) when (ex is SecurityTokenValidationException || ex is SignatureVerificationFailedException)
{
Logger.ErrorFormat(ex.Message, ex);
return null;
}因此,您不必错误地捕获其他SecurityTokenException的子类型。
发布于 2016-07-14 11:54:59
例如,您可以通过仅在发生故障时使用return来简化return语句。
下面是一些伪代码示例:
bool success;
try
{
success = foo();
}
catch (SecurityTokenValidationException ex)
{
Logger.ErrorFormat(ex.Message, ex);
}
catch (SignatureVerificationFailedException ex)
{
Logger.ErrorFormat(ex.Message, ex);
}
if(success)
{
return result;
}
return null;或者另一个例子。
try
{
return foo();
}
catch (SecurityTokenValidationException ex)
{
Logger.ErrorFormat(ex.Message, ex);
}
catch (SignatureVerificationFailedException ex)
{
Logger.ErrorFormat(ex.Message, ex);
}
return null;发布于 2016-07-14 12:14:35
最后,我使用了一个异常,它是上述两个异常的基类。
换句话说,
try
{
foo();
}
catch (SecurityTokenException ex)
{
Logger.ErrorFormat(ex.Message, ex);
return null;
}SecurityTokenValidationException1和SignatureVerificationFailedException都来自于SecurityTokenException。
现在,代码分析是愉快的:)
https://stackoverflow.com/questions/38372017
复制相似问题