是否有任何方法可以编写LINQ样式的"简写"代码,用于遍历抛出Exception的所有级别的InnerException?我宁愿写它而不是调用扩展函数(如下所示)或继承Exception
类.
static class Extensions
{
public static string GetaAllMessages(this Exception exp)
{
string message = string.Empty;
Exception innerException = exp;
do
{
message = message + (string.IsNullOrEmpty(innerException.Message) ? string.Empty : innerException.Message);
innerException = innerException.InnerException;
}
while (innerException != null);
return message;
}
};
Run Code Online (Sandbox Code Playgroud)
Jef*_*ado 80
不幸的是,LINQ不提供可以处理分层结构的方法,只提供集合.
我实际上有一些扩展方法可以帮助做到这一点.我手头没有确切的代码但它们是这样的:
// all error checking left out for brevity
// a.k.a., linked list style enumerator
public static IEnumerable<TSource> FromHierarchy<TSource>(
this TSource source,
Func<TSource, TSource> nextItem,
Func<TSource, bool> canContinue)
{
for (var current = source; canContinue(current); current = nextItem(current))
{
yield return current;
}
}
public static IEnumerable<TSource> FromHierarchy<TSource>(
this TSource source,
Func<TSource, TSource> nextItem)
where TSource : class
{
return FromHierarchy(source, nextItem, s => s != null);
}
Run Code Online (Sandbox Code Playgroud)
然后在这种情况下,你可以这样做来枚举例外:
public static string GetaAllMessages(this Exception exception)
{
var messages = exception.FromHierarchy(ex => ex.InnerException)
.Select(ex => ex.Message);
return String.Join(Environment.NewLine, messages);
}
Run Code Online (Sandbox Code Playgroud)
k.m*_*k.m 72
你的意思是这样的?
public static class Extensions
{
public static IEnumerable<Exception> GetInnerExceptions(this Exception ex)
{
if (ex == null)
{
throw new ArgumentNullException("ex");
}
var innerException = ex;
do
{
yield return innerException;
innerException = innerException.InnerException;
}
while (innerException != null);
}
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以LINQ覆盖整个异常层次结构,如下所示:
exception.GetInnerExceptions().Where(e => e.Message == "Oops!");
Run Code Online (Sandbox Code Playgroud)
Vla*_*har 28
这段代码怎么样:
private static string GetExceptionMessages(this Exception e, string msgs = "")
{
if (e == null) return string.Empty;
if (msgs == "") msgs = e.Message;
if (e.InnerException != null)
msgs += "\r\nInnerException: " + GetExceptionMessages(e.InnerException);
return msgs;
}
Run Code Online (Sandbox Code Playgroud)
用法:
Console.WriteLine(e.GetExceptionMessages())
Run Code Online (Sandbox Code Playgroud)
输出示例:
没有端点侦听http://nnn.mmm.kkk.ppp:8000/routingservice/router可以接受该消息.这通常是由错误的地址或SOAP操作引起的.有关更多详细信息,请参阅InnerException(如果存在).
InnerException:无法连接到远程服务器
InnerException:无法建立连接,因为目标计算机主动拒绝它127.0.0.1:8000
Jiř*_*ník 20
我知道这很明显,但也许不是全部.
exc.ToString();
Run Code Online (Sandbox Code Playgroud)
这将遍历所有内部异常并返回所有消息,但与堆栈跟踪等一起返回.
4th*_*hex 13
您不需要扩展方法或递归调用:
try {
// Code that throws exception
}
catch (Exception e)
{
var messages = new List<string>();
do
{
messages.Add(e.Message);
e = e.InnerException;
}
while (e != null) ;
var message = string.Join(" - ", messages);
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*n.K 10
LINQ通常用于处理对象集合.但是,可以说,在您的情况下,没有对象的集合(但是图形).因此,即使一些LINQ代码可能是可能的,恕我直言,它将是相当复杂或人为的.
另一方面,您的示例看起来像扩展方法实际上合理的一个主要示例.更不用说重用,封装等问题.
我会继续使用扩展方法,虽然我可能已经这样实现了:
public static string GetAllMessages(this Exception ex)
{
if (ex == null)
throw new ArgumentNullException("ex");
StringBuilder sb = new StringBuilder();
while (ex != null)
{
if (!string.IsNullOrEmpty(ex.Message))
{
if (sb.Length > 0)
sb.Append(" ");
sb.Append(ex.Message);
}
ex = ex.InnerException;
}
return sb.ToString();
}
Run Code Online (Sandbox Code Playgroud)
但这主要是品味问题.
我不这么认为,异常不是IEnumerable,所以你不能自己执行linq查询.
返回内部异常的扩展方法可以像这样工作
public static class ExceptionExtensions
{
public static IEnumerable<Exception> InnerExceptions(this Exception exception)
{
Exception ex = exception;
while (ex != null)
{
yield return ex;
ex = ex.InnerException;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用linq查询附加所有消息,如下所示:
var allMessageText = string.Concat(exception.InnerExceptions().Select(e => e.Message + ","));
Run Code Online (Sandbox Code Playgroud)
小智 6
要添加到其他人,您可能希望让用户决定如何分隔消息:
public static string GetAllMessages(this Exception ex, string separator = "\r\nInnerException: ")
{
if (ex.InnerException == null)
return ex.Message;
return ex.Message + separator + GetAllMessages(ex.InnerException, separator);
}
Run Code Online (Sandbox Code Playgroud)
这里提出的大多数解决方案都存在以下实施错误:
null
异常AggregateException
更好的实现是这样的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public static string AggregateMessages(this Exception ex) =>
ex.GetInnerExceptions()
.Aggregate(
new StringBuilder(),
(sb, e) => sb.AppendLine(e.Message),
sb => sb.ToString());
public static IEnumerable<Exception> GetInnerExceptions(this Exception ex, int maxDepth = 5)
{
if (ex == null || maxDepth <= 0)
{
yield break;
}
yield return ex;
if (ex is AggregateException ax)
{
foreach(var i in ax.InnerExceptions.SelectMany(ie => GetInnerExceptions(ie, maxDepth - 1)))
yield return i;
}
foreach (var i in GetInnerExceptions(ex.InnerException, maxDepth - 1))
yield return i;
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
try
{
// ...
}
catch(Exception e)
{
Log.Error(e, e.AggregateMessages());
}
Run Code Online (Sandbox Code Playgroud)
public static string GetExceptionMessage(Exception ex)
{
if (ex.InnerException == null)
{
return string.Concat(ex.Message, System.Environment.NewLine, ex.StackTrace);
}
else
{
// Retira a última mensagem da pilha que já foi retornada na recursividade anterior
// (senão a última exceção - que não tem InnerException - vai cair no último else, retornando a mesma mensagem já retornada na passagem anterior)
if (ex.InnerException.InnerException == null)
return ex.InnerException.Message;
else
return string.Concat(string.Concat(ex.InnerException.Message, System.Environment.NewLine, ex.StackTrace), System.Environment.NewLine, GetExceptionMessage(ex.InnerException));
}
}
Run Code Online (Sandbox Code Playgroud)