有时候innerException是空的。
所以以下代码可能会失败:
repEvent.InnerException = ex.InnerException.Message;
有没有一种快速的三元方式来检查 innerException 是否为 null?
有时候innerException是空的。
所以以下代码可能会失败:
repEvent.InnerException = ex.InnerException.Message;
有没有一种快速的三元方式来检查 innerException 是否为 null?
到目前为止,已经有很棒的答案了。不过,有时候可能会有多层嵌套的异常。如果想要获取最初引发的根异常,无论有多深,可以尝试这样做:
public static class ExceptionExtensions
{
public static Exception GetOriginalException(this Exception ex)
{
if (ex.InnerException == null) return ex;
return ex.InnerException.GetOriginalException();
}
}
并且在使用中:
repEvent.InnerException = ex.GetOriginalException();
这是你在寻找的东西吗?
String innerMessage = (ex.InnerException != null)
? ex.InnerException.Message
: "";
!=
改成 ==
会更加简洁易懂? - Noldorin很有趣,我找不到Exception.GetBaseException()的问题?
repEvent.InnerException = ex.GetBaseException().Message;
repEvent.InnerException = ex.InnerException == null ?
null : ex.InnerException.Message;
mind
也返回一个 string
。我只是根据代码假定你调用了 InnerException
属性(只是为了混淆吗?)。不过没关系。
@Andrew: 谢谢。虽然我完全不介意,但 +1 给你的礼貌。 - Noldorin为什么这些答案中有那么多递归?
public static class ExceptionExtensions
{
public static Exception GetOriginalException(this Exception ex)
{
while(ex.InnerException != null)ex = ex.InnerException;
return ex;
}
}
看起来这是一种更加直观的实现方式。
这是一个旧问题,但对于未来的读者:
除了已经发布的答案,我认为正确的做法(当您可以有多个InnerException时)是Exception.GetBaseException方法
如果您想要异常实例,应该这样做:
repEvent.InnerException = ex.GetBaseException();
如果您只是想通过这种方式查找消息:
repEvent.InnerException = ex.GetBaseException().Message;
使用C# 6.0,您可以使用以下代码:
string message = exception.InnerException?.Message ?? ""
;
这行代码与以下代码类似:
string message = exception.InnerException == null ? "" : exception.InnerException.Message
.
(ex.InnerException?.Message??"")
方便、可读且安全。 - dakabcatch (Exception exception)
{
Logger.Error(exception.Message);
while (exception.InnerException != null)
{
exception = exception.InnerException;
Logger.Error(exception);
}
}
while (ex.InnerException != null)
方法,发现它非常有用。然而,有时它可能变得非常冗长。 - Zimanopublic string GetInnerException(Exception ex)
{
if (ex.InnerException != null)
{
return string.Format("{0} > {1} ", ex.InnerException.Message, GetInnerException(ex.InnerException));
}
return string.Empty;
}