.NET自定义AggregateException的Message被覆盖,如何阻止?
解决AggregateException子类自定义Message被自动追加内部异常信息的问题
问题本质
AggregateException的Message属性并非直接存储构造函数传入的字符串,而是动态生成的——它会自动将传入的消息与所有内部异常的信息拼接在一起。这就是为什么你传入自定义截断后的消息,最终仍会被追加完整内部异常信息的原因。
解决方案
要完全自定义Message,必须重写Exception类的Message属性。由于AggregateException本身重写了基类的Message,你的子类需要再次重写该属性,直接返回自定义构建的消息。
修改后的代码示例
public class MyDerivedAggregateException : AggregateException { private readonly string _customMessage; public MyDerivedAggregateException( string message, IEnumerable<Exception> innerExceptions, bool isEarlyTermination ) : base(string.Empty, innerExceptions) // 传入空字符串,避免基类自动拼接内容 { _customMessage = BuildMessage(message, innerExceptions.ToList(), isEarlyTermination); } // 重写Message属性,返回自定义消息 public override string Message => _customMessage; private static string BuildMessage(string message, List<Exception> innerExs) { var sb = new StringBuilder(); sb.AppendLine(message); int numToShow = Math.Min(5, innerExs.Count); int numNotShown = innerExs.Count - numToShow; for (int i = 0; i < numToShow; i++) sb.AppendLine($"Exception {i + 1}: {innerExs[i].Message}"); if (numNotShown > 0) sb.AppendLine($"({numNotShown} more exceptions not shown...)"); return sb.ToString(); } // 可选:重写ToString(),自定义输出格式,避免默认的冗余内容 public override string ToString() { return $"{GetType().FullName}: {_customMessage}{Environment.NewLine}{StackTrace}"; } }
关键说明
- 基类构造函数传空字符串:避免
AggregateException内部生成包含所有内部异常的消息,从源头杜绝冗余内容的产生。 - 存储自定义消息:将构建好的自定义消息存入私有字段
_customMessage,确保后续访问时直接返回该值。 - 重写Message属性:完全绕过
AggregateException的动态消息生成逻辑,直接返回自定义内容。 - 可选重写ToString():如果需要控制异常的完整输出格式(比如避免默认输出所有内部异常的堆栈),可以重写该方法,自定义输出内容。
效果验证
修改后,捕获异常并访问ex.Message时,只会得到你自定义的截断消息,不会附加任何.NET自动生成的冗余内部异常信息,彻底解决日志过载问题。
内容的提问来源于stack exchange,提问作者Bassinator
相关产品推荐
相关产品推荐

