Skip to content

Commit 84ebd48

Browse files
committed
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.
1 parent 1b6a42d commit 84ebd48

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

src/Serilog.Expressions/Templates/Compilation/CompiledExceptionToken.cs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,17 @@ public override void Evaluate(EvaluationContext ctx, TextWriter output)
3636
if (ctx.LogEvent.Exception is null)
3737
return;
3838

39-
var lines = new StringReader(ctx.LogEvent.Exception.ToString());
39+
StringReader lines;
40+
try
41+
{
42+
lines = new StringReader(ctx.LogEvent.Exception.ToString());
43+
}
44+
catch (Exception e)
45+
{
46+
lines = new StringReader(
47+
$"[Exception.ToString() failed: {e.Message}] Original exception type: {ctx.LogEvent.Exception?.GetType().FullName}, message: {ctx.LogEvent.Exception?.Message}{Environment.NewLine}");
48+
}
49+
4050
while (lines.ReadLine() is { } nextLine)
4151
{
4252
var style = nextLine.StartsWith(StackFrameLinePrefix) ? _secondaryText : _text;

0 commit comments

Comments
 (0)