From 84ebd488a9d75c9929303ff6235bf767e1bc89ba Mon Sep 17 00:00:00 2001 From: Krisbiradar Date: Fri, 29 Aug 2025 00:41:33 +0530 Subject: [PATCH] Handle Exception.ToString() failures in template compilation Wrap Exception.ToString() in a try-catch block to handle potential failures. If an exception occurs, output a fallback message with details about the original exception and the error encountered. --- .../Templates/Compilation/CompiledExceptionToken.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/Serilog.Expressions/Templates/Compilation/CompiledExceptionToken.cs b/src/Serilog.Expressions/Templates/Compilation/CompiledExceptionToken.cs index d7a85b2..b74b11b 100644 --- a/src/Serilog.Expressions/Templates/Compilation/CompiledExceptionToken.cs +++ b/src/Serilog.Expressions/Templates/Compilation/CompiledExceptionToken.cs @@ -36,7 +36,17 @@ public override void Evaluate(EvaluationContext ctx, TextWriter output) if (ctx.LogEvent.Exception is null) return; - var lines = new StringReader(ctx.LogEvent.Exception.ToString()); + StringReader lines; + try + { + lines = new StringReader(ctx.LogEvent.Exception.ToString()); + } + catch (Exception e) + { + lines = new StringReader( + $"[Exception.ToString() failed: {e.Message}] Original exception type: {ctx.LogEvent.Exception?.GetType().FullName}, message: {ctx.LogEvent.Exception?.Message}{Environment.NewLine}"); + } + while (lines.ReadLine() is { } nextLine) { var style = nextLine.StartsWith(StackFrameLinePrefix) ? _secondaryText : _text;