C# 检查内部异常的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1456563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to check for inner exception?
提问by JL.
I know sometimes innerException is null
我知道有时innerException 为空
So the following might fail:
所以以下可能会失败:
repEvent.InnerException = ex.InnerException.Message;
Is there a quick ternary way to check if innerException is null or not?
是否有一种快速的三元方法来检查innerException 是否为空?
采纳答案by Andrew Hare
Is this what you are looking for?
这是你想要的?
String innerMessage = (ex.InnerException != null)
? ex.InnerException.Message
: "";
回答by Dan Tao
Yes:
是的:
if (ex.InnerException == null) {
// then it's null
}
回答by Noldorin
The simplest solution is to use a basic conditional expression:
最简单的解决方案是使用基本的条件表达式:
repEvent.InnerException = ex.InnerException == null ?
null : ex.InnerException.Message;
回答by jrista
Great answers so far. On a similar, but different note, sometimes there is more than one level of nested exceptions. If you want to get the root exception that was originally thrown, no matter how deep, you might try this:
到目前为止很好的答案。类似但不同的是,有时嵌套异常不止一层。如果你想得到最初抛出的根异常,不管多深,你可以试试这个:
public static class ExceptionExtensions
{
public static Exception GetOriginalException(this Exception ex)
{
if (ex.InnerException == null) return ex;
return ex.InnerException.GetOriginalException();
}
}
And in use:
并在使用中:
repEvent.InnerException = ex.GetOriginalException();
回答by Jan Remunda
Sometimes also InnerException has an InnerException, so you can use a recursive function for it:
有时 InnerException 也有一个 InnerException,所以你可以为它使用递归函数:
public string GetInnerException(Exception ex)
{
if (ex.InnerException != null)
{
return string.Format("{0} > {1} ", ex.InnerException.Message, GetInnerException(ex.InnerException));
}
return string.Empty;
}
回答by csharptest.net
That's funny, I can't find anything wrong with Exception.GetBaseException()?
这很有趣,我找不到Exception.GetBaseException()有什么问题?
repEvent.InnerException = ex.GetBaseException().Message;
回答by Diego
Its an old question but for future readers:
这是一个老问题,但对于未来的读者:
In addition to the answers already posted I think the correct way to do this (when you can have more than one InnerException) is Exception.GetBaseException Method
除了已经发布的答案之外,我认为正确的方法(当您可以有多个 InnerException 时)是Exception.GetBaseException Method
If you want the exception instance you should do this:
如果你想要异常实例,你应该这样做:
repEvent.InnerException = ex.GetBaseException();
If you are only looking for the message this way:
如果您只是通过这种方式寻找消息:
repEvent.InnerException = ex.GetBaseException().Message;
回答by Yaur
Why so much recursion in these answers?
为什么在这些答案中有如此多的递归?
public static class ExceptionExtensions
{
public static Exception GetOriginalException(this Exception ex)
{
while(ex.InnerException != null)ex = ex.InnerException;
return ex;
}
}
Seems like a much more straight forward way to implement this.
似乎是实现这一点的更直接的方法。
回答by Ognyan Dimitrov
Here is another possible implementation that appends the messages and stack traces so we get them full:
这是另一种可能的实现,它附加消息和堆栈跟踪,以便我们将它们填满:
private static Tuple<string, string> GetFullExceptionMessageAndStackTrace(Exception exception)
{
if (exception.InnerException == null)
{
if (exception.GetType() != typeof(ArgumentException))
{
return new Tuple<string, string>(exception.Message, exception.StackTrace);
}
string argumentName = ((ArgumentException)exception).ParamName;
return new Tuple<string, string>(String.Format("{0} With null argument named '{1}'.", exception.Message, argumentName ), exception.StackTrace);
}
Tuple<string, string> innerExceptionInfo = GetFullExceptionMessageAndStackTrace(exception.InnerException);
return new Tuple<string, string>(
String.Format("{0}{1}{2}", innerExceptionInfo.Item1, Environment.NewLine, exception.Message),
String.Format("{0}{1}{2}", innerExceptionInfo.Item2, Environment.NewLine, exception.StackTrace));
}
[Fact]
public void RecursiveExtractingOfExceptionInformationOk()
{
// Arrange
Exception executionException = null;
var iExLevelTwo = new NullReferenceException("The test parameter is null");
var iExLevelOne = new ArgumentException("Some test meesage", "myStringParamName", iExLevelTwo);
var ex = new Exception("Some higher level message",iExLevelOne);
// Act
var exMsgAndStackTrace = new Tuple<string, string>("none","none");
try
{
exMsgAndStackTrace = GetFullExceptionMessageAndStackTrace(ex);
}
catch (Exception exception)
{
executionException = exception;
}
// Assert
Assert.Null(executionException);
Assert.True(exMsgAndStackTrace.Item1.Contains("The test parameter is null"));
Assert.True(exMsgAndStackTrace.Item1.Contains("Some test meesage"));
Assert.True(exMsgAndStackTrace.Item1.Contains("Some higher level message"));
Assert.True(exMsgAndStackTrace.Item1.Contains("myStringParamName"));
Assert.True(!string.IsNullOrEmpty(exMsgAndStackTrace.Item2));
Console.WriteLine(exMsgAndStackTrace.Item1);
Console.WriteLine(exMsgAndStackTrace.Item2);
}
回答by Toddams
With C# 6.0 you can use:
使用 C# 6.0,您可以使用:
string message = exception.InnerException?.Message ?? ""
;
string message = exception.InnerException?.Message ?? ""
;
This line of code is similar to:
这行代码类似于:
string message = exception.InnerException == null ? "" : exception.InnerException.Message
.
string message = exception.InnerException == null ? "" : exception.InnerException.Message
.
https://msdn.microsoft.com/en-us/library/ty67wk28.aspx